Same old question  (rows to columns using pl/sql)

Hi all,
i am re-posting the same requirement, please do the needful.
I need a query to convert row value into column delimited by space.
Dont need any column names just values.
create table tb_row_2_col (id number,val varchar2(100));
insert into tb_row_2_col values (1,'col1');
insert into tb_row_2_col values (1,'col2');
insert into tb_row_2_col values (1,'col3');
insert into tb_row_2_col values (2,'col4');
insert into tb_row_2_col values (2,'col5');
commit;
SQL> select * from tb_row_2_col;
ID VAL
1 col1
1 col2
1 col3
2 col4
2 col5
SQL>
if i execute a query the output should be like this. Please dont used decode/case.
need to use loop to do the needful.
1 col1 col2 col3
2 col4 col5
Priya.

I doubted PL/SQL will be much faster, bjut here it goes:
declare
    v_id number;
    v_prev_id number;
    v_val varchar2(100);
    v_combined_val varchar2(4000);
    cursor v_cur is select id,val from tb_row_2_col order by id,val;
begin
    open v_cur;
    fetch v_cur into v_prev_id,v_combined_val;
    loop
      fetch v_cur into v_id,v_val;
      exit when v_cur%notfound;
      if v_id = v_prev_id
        then
          v_combined_val := v_combined_val || ' ' || v_val;
        else
          dbms_output.put_line(rpad(v_prev_id,5) || v_combined_val);
          v_prev_id := v_id;
          v_combined_val := v_val;
      end if;
    end loop;
    dbms_output.put_line(rpad(v_prev_id,5) || v_combined_val);
    close v_cur;
end;
1    col1 col2 col3
2    col4 col5
PL/SQL procedure successfully completed.
SQL> SY.

Similar Messages

  • Converting rows to columns using t-sql

    Hi All,
    I have a table with 3 columns, let say ID1 , ID2, Flag
    My Source data looks like this..
    ID1    ID2       Flag
    1         1            0
    1         2            0
    1         3            0
    2         7            0
    2         8            1
    2         9            0
    4         5            0
    Now My output should look like this..
    ID1     Newcol1     NewFlag1     Newcol2     NewFlag2   Newcol3    NewFlag3
    1           1                    0                  
     2                   0                3                
    0
    2           7                    0               
        8                   1                9                
    0
    4           5                    0                  
     null               null            null              null
    Basically I want to convert rows to columns and to get above output I need t-SQL query.
    Thanks in advance
    RH
    sql

    You can do it by this query:
    declare @table table ( ID1 int, ID2 int, Flag int)
    insert @table values ( 1,1,0 ),( 1,2,0 ),( 1,3,0 ),( 2,7,0 ),( 2,8,1 ),( 2,9,0 ),( 4,5,0 )
    WITH cte1
    AS ( SELECT Id1 ,
    ROW_NUMBER() over (partition by ID1 order by ID1 ) as Sequence ,
    ID2 ,
    Flag
    FROM @table
    cte2
    AS ( SELECT Id1 ,
    ColumnTitle + LTRIM(RTRIM(STR(Sequence))) AS ColumnTitle ,
    ColumnData
    FROM cte1 UNPIVOT ( ColumnData FOR ColumnTitle IN ( [ID2], [Flag] ) ) AS UP
    SELECT Id1 ,
    [ID21] FirstID2 ,
    [Flag1] FirstFlag ,
    [ID22] SecondID2 ,
    [Flag2] SecondFlag ,
    [ID23] ThirdID2 ,
    [Flag3] ThirdFlag
    FROM cte2 PIVOT ( MAX(ColumnData) FOR ColumnTitle IN ( [ID21],
    [Flag1],
    [ID22],
    [Flag2],
    [ID23],
    [Flag3] ) ) PV
    If you want to know more detail, please visit my old article about this method:
    T-SQL: PIVOT Ordered pair Columns
    T-SQL e-book by TechNet Wiki Community
    My Blog
    My Articles

  • Convert rows to columns using t-sql

    Hi All,
    My source data looks like this..
    ID      Name    Rn
    1       Sam      1
    1       John      2
    1       Greg      1
    1       Smith     2
    1        Aron      1
    2       Brad       1
    2       Kevin      2
    2       Alex        1
    2       Jeff          2
    I need t-sql to get below output..Put Name into two columns, When Rn=1 Then Name1, When Rn=2 Then Name2.
     ID      Name1    Rn1  Name2    Rn2
      1       Sam        1       John       2
      1       Greg        1       Smith     2
      1       Aron        1        null      null
      2       Brad         1       Kevin     2   
      2       Alex          1       Jeff        2
    Thanks!
    sql

    to achieve this you need to have either 1. some unique key that can refer rn=1 and 2 for each person in each group or 2 . identity value column where, row number are enforce order of rn=1 and rn=2
    Vinay''s solution works until you have  do not have  last name for one row but have some data for the same group id
    like : 
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'Sam',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'John',2)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'Greg',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'Smith',2)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'Aron',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'newfirstname',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (1,'wronglastname',2)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (2,'Brad',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (2,'Kevin',2)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (2,'Alex',1)
    INSERT INTO #temp1(ID,Name,Rn) VALUES (2,'Jeff',2)
    this would work but as said you need some key to identify uniquely.
    create table #Tmp (no int identity(1,1),ID int,Name varchar(20),Rn int)
    insert into #Tmp
    values
    (1,'Sam',1),
    (1,'John',2),
    (1,'Greg',1),
    (1,'Smith',2),
    (1,'Aron',1),
    (2,'Brad',1),
    (2,'Kevin',2),
    (2,'Alex',1),
    (2,'Jeff',2)
    Select distinct A.ID,A.Name,A.RN,B.NAme,B.Rn
    from(
    (select A.ID,A.Name,A.RN,A.no from #tmp A where A.rn=1) A FULL OUTER JOIN
    (select A.ID,A.Name,A.RN,A.no from #tmp A where A.rn=2) B on a.ID=B.id and A.no=B.no-1)
    drop table #tmp
    Hope it Helps!!

  • Table name input. and output i need  all rows and columns  using procedures

    hi,
    question: table name input. and output i need all rows and columns by using procedures.
    thanks,
    To All

    An example of using DBMS_SQL package to execute dynamic SQL (in this case to generate CSV data in a file)...
    As sys user:
    CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
    GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
    /As myuser:
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                         ,p_dir IN VARCHAR2
                                         ,p_header_file IN VARCHAR2
                                         ,p_data_file IN VARCHAR2 := NULL) IS
      v_finaltxt  VARCHAR2(4000);
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_fh        UTL_FILE.FILE_TYPE;
      v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
    BEGIN
      c := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      d := DBMS_SQL.EXECUTE(c);
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
        END CASE;
      END LOOP;
      -- This part outputs the HEADER
      v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
      FOR j in 1..col_cnt
      LOOP
        v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
      END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
      UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      IF NOT v_samefile THEN
        UTL_FILE.FCLOSE(v_fh);
      END IF;
      -- This part outputs the DATA
      IF NOT v_samefile THEN
        v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
      END IF;
      LOOP
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        EXIT WHEN v_ret = 0;
        v_finaltxt := NULL;
        FOR j in 1..col_cnt
        LOOP
          CASE rec_tab(j).col_type
            WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
            WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                        v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                        v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
          ELSE
            v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
          END CASE;
        END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
        UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      END LOOP;
      UTL_FILE.FCLOSE(v_fh);
      DBMS_SQL.CLOSE_CURSOR(c);
    END;This allows for the header row and the data to be written to seperate files if required.
    e.g.
    SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
    PL/SQL procedure successfully completed.Output.txt file contains:
    empno,ename,job,mgr,hiredate,sal,comm,deptno
    7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
    7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
    7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
    7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
    7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
    7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
    7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
    7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
    7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
    7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
    7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
    7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
    7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
    7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
    Adapt to output different datatypes and styles are required.

  • Converting rows to columns using dynamic query.

    I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
    declare
        lv_sql varchar2(32767) := null ;
    begin
        lv_sql := 'SELECT Iplineno ';
        for lv_rec in (SELECT distinct vendor from bidtabs  where letting = '10021200' and call ='021')
        loop
            lv_sql :=   lv_sql
                        || CHR(10)
                        || ', MAX( DECODE( vendor, '
                        || chr(39)
                        || lv_rec.vendor
                        || CHR(39)
                        || ', bidprice, NULL ) ) as "'
                        || lv_rec.vendor
                        || '" ' ;
        end loop;
        lv_sql :=   lv_sql
                    || CHR(10)
                    || 'FROM bidtabs  where letting =  ''10021200''  and call =  ''021''  and lineflag = ''L''  '
                    || CHR(10)
                    || 'GROUP BY iplineno ;' ;
    here is the result
    BIDPRICE     CALL     IPLINENO     LETTING     VENDOR
    9,585     021     0010     10021200     C0104        
    1,000     021     0020     10021200     C0104        
    1,000     021     0030     10021200     C0104        
    17     021     0040     10021200     C0104        
    5     021     0050     10021200     C0104        
    11,420     021     0010     10021200     K0054        
    1,100     021     0020     10021200     K0054        
    1,100     021     0030     10021200     K0054        
    5     021     0040     10021200     K0054        
    3     021     0050     10021200     K0054        
    8,010     021     0010     10021200     V070         
    900     021     0020     10021200     V070         
    1,320     021     0030     10021200     V070         
    11     021     0040     10021200     V070         
    3     021     0050     10021200     V070         
    and here is the desired output
    CALL     IPLINENO     LETTING      C0104              K0054              V070         
    021     0010     10021200      9,585                     11,420                                   8,010
    021     0020     10021200      1,000       1,100     900
    021     0030     10021200      1,000     1,100     1,320
    021     0040     10021200       17     5     11
    021     0050     10021200      5     3     3

    Here is the error message I am getting:
    RA-06550: line 22, column 43:
    PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    pipe

  • Converting key figures from rows to column using DSO and start routine

    Hi SDNer:
    I need some help to convert key figures from rows to column.
    The source is DSO 1 and I am thinking about writing ABAP in the start routine to do the conversion. The target is DSO2.
    Below is the  more detail information with example. Basically, for each record in DSO 1 I need to create 3 records (because there are 3 KF's) and output to DSO2.
    I would really appreciate some help on this.Thank you.
    Tony
    DSO 1 data format (SOURCE)
    Period   ID   KF1  KF2  KF3
    200702 100  300  200   750
    Output to DSO 2 (TARGET)
    Period   ID    KF  LABEL
    200702 100  300  KF1
    200702 100  200  KF2
    200702 100  750  KF3

    This is the code in BI 7.0.
    u need to put a field "Label" in DSO1. u dont need to populate this in DSO1 but it helps the code to populate the field in DSO2.
    DATA: wa_result TYPE _ty_s_sc_1,
    t_result TYPE STANDARD TABLE OF _ty_s_sc_1.
    DATA:counter(2) TYPE n.
    LOOP AT SOURCE_PACKAGE INTO wa_result.
    counter =0.
    while counter < 3 .
    wa_result- Period = wa_result-Period.
    wa_result- ID = wa_result-ID.
    if counter  = 0.
    wa_result- KF1 = wa_result-KF1.
    wa_result- Label = 'KF1'.
    elseif counter = 1.
    wa_result- KF1 = wa_result-KF2.
    wa_result- Label = 'KF2'.
    else.
    wa_result- KF1 = wa_result-KF3.
    wa_result- Label = 'KF3'.
    endif.
    APPEND wa_result TO t_result.
    counter = counter+1.
    endwhile.
    endloop.
    CLEAR: SOURCE_PACKAGE,wa_result.
    LOOP AT t_result INTO wa_result.
    APPEND wa_result TO SOURCE_PACKAGE.
    ENDLOOP.

  • Rows to Columns within PL/SQL or sql.

    Hi i need to get this data which is being extracted using a sql query with a prior by clause and is being displayed as rows. to display as seperate column on one row., the values need to be in their own column on the same row...
    table layout
    Level 1   Level2     Level3    Level4    Level5 
    column1     column2     column3
    270767     197851            1
    64631     230693            2
    33115     230481            3
    229148     209655            4
    So i need to get these rows into the columns on the table........ But the rows can go upto 11 and beyond so i will create a table with lots of columns, but for now
    just using 5 , But i want the script so it can just keep going through the columns not just restricted to 5....

    Hi,
    Use SYS_CONNECT_BY_PATH to get a delimited list of all the values, in order by LEVEL.
    I would just display that: you don't have to know how many LEVELs there might be, and therefore how many columns you have to hard-code into the query.
    If you really do have to split the list into separate columns, use
    REGEXP_SUBSTR ( sys_connect_by_path_results
                  , '[^,]+'    -- where , is the delimiter: any other single character would do as well
                  , 1
                  , n
                  )to get the n-th item on the list. You have to hard-code the worst case (the maximum number of levels), or use dynamic SQL to do it for you.
    For a more specific answer, post a more specific question.
    Include:
    (1) The version of Oracle (and any other relevant software) you're using
    (2) A little sample data (just enough to show what the problem is) from all the relevant tables
    (3) The results you want from that data
    (4) Your best attempt so far (formatted)
    Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
    If you can present your problem using commonly available tables (for example, tables in scott schema, where emp has a nice hierarchy), then you can omit (2).
    Formatted tabular output is okay for (3). Type these 6 characters
    (small letters only, inside curly brackets) before and after formatted, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Referring to Cursor Row and Column in Dynamic SQL

    I have a procedure that dynamically reads a schema name and table name from an input table. The code then needs to loop through all rows and columns of each table and output the data. I'm 95% done with what I want to accomplish, but there is one small bug. The line dbms_output.put(*col.column_name* || '',''); ' ||
    should refer to something like rec.col.column_name so that it gets the column of the current record. Right now it just displays the column name for each record instead of the actual value. Can anyone help me tweak the code to get the actual value?
    CREATE OR REPLACE PACKAGE BODY some_proc IS
    -- Function and procedure implementations
    PROCEDURE create_files IS
    CURSOR c_tbls IS
    SELECT * FROM tbl_list;
    l_sql VARCHAR2(4000);
    BEGIN
    --Loop through all tables
    FOR tbl IN c_tbls LOOP
    l_sql := 'DECLARE ' || ' CURSOR c_tbl_recs IS ' || ' SELECT * ' ||
    ' FROM ' || tbl.schema_name || '.' || tbl.table_name || '; ' ||
    ' t_tbl_rowtype c_tbl_recs%ROWTYPE; ' || 'BEGIN ' ||
    ' FOR rec IN c_tbl_recs LOOP ' ||
    ' FOR col IN (SELECT column_name ' ||
    ' FROM dba_tab_cols ' ||
    ' WHERE owner = ''' || tbl.schema_name || '''' ||
    ' AND table_name = ''' || tbl.table_name || '''' ||
    ' ORDER BY column_id) LOOP ' ||
    *' dbms_output.put(col.column_name || '',''); ' ||* ' END LOOP; dbms_output.put_line(''''); END LOOP; ' ||
    'END; ';
    --dbms_output.put_line(l_sql);
    EXECUTE IMMEDIATE l_sql;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line(SQLERRM);
    END;
    END;

    Is it this what you are looking for?
    (it took some minutes)
    create or replace
    package some_proc is
    procedure create_files;
    end;
    CREATE OR REPLACE
    PACKAGE BODY some_proc
    IS
      -- Function and procedure implementations
    PROCEDURE create_files
    IS
      CURSOR c_tbls
      IS
        SELECT * FROM tbl_list;
      CURSOR c_cols (p_table_owner VARCHAR2, p_table_name VARCHAR2)
      IS
        SELECT column_name
        FROM all_tab_columns
        WHERE owner   =p_table_owner
        AND table_name=p_table_name
        ORDER BY all_tab_columns.column_id;
      l_sql     VARCHAR2(32000);
      separator VARCHAR2(1):=';';
    BEGIN
      --Loop through all tables
      FOR tbl IN c_tbls
      LOOP
        dbms_output.put_line('TABLE: '||tbl.schema_name||'.'||tbl.table_name);
        l_sql := 'DECLARE ' ;
        l_sql := l_sql|| '  CURSOR c_tbl_recs IS ' ;
        l_sql := l_sql||'    SELECT * FROM ' || tbl.schema_name || '.' || tbl.table_name || '; ' ;
        l_sql := l_sql||'    linenr number:=1; ';
        l_sql := l_sql||'BEGIN ' ;
        l_sql := l_sql|| ' FOR rec IN c_tbl_recs LOOP ';
        FOR c IN c_cols(tbl.schema_name,tbl.table_name)
        LOOP
          l_sql:=l_sql ||' if linenr=1 then  dbms_output.put('''||c.column_name||''||separator||'''); end if; ' ;
        END LOOP;
        l_sql :=l_sql||'  dbms_output.put_line(''''); linenr:=linenr+1; ';
        FOR c IN c_cols(tbl.schema_name,tbl.table_name)
        LOOP
          l_sql:=l_sql ||' dbms_output.put(rec.'||c.column_name||'||'''||separator||'''); ' ;
        END LOOP;
        l_sql:=l_sql||'  end loop; ';
        l_sql:=l_sql||'  dbms_output.put_line(''''); ';
        l_sql:=l_sql||'  dbms_output.put_line(''''); ';
        l_sql:=l_sql||'end;';
        EXECUTE IMMEDIATE l_sql;
      END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line(SQLERRM);
    END;
    END;
    /

  • How to test if there are duplicate values in a column using PL/SQL

    Hello,
    I want to be able to test if there are duplicate values (VARCHAR2) in a particular column of the database using PL/SQL.
    Thanks
    Douglas

    If I have understood your requirement, then you are asking for a query like following.
    Select column_name from Tbl_name
    group by column_name
    having count(*) > 1;

  • Split one column value into two columns using t-sql

    Hi All,
    I have one varchar column in a table.
    Col1
    ABC-12C4
    BC-A345
    CD
    XYZ
    How to split this into two columns like this using t-sql
    Col1   Col2
    ABC    12C4
    BC      A345
    CD     
    XYZ
    Thanks,
    RH
    sql

    assuming a static delimiter, and the split will end up with a max of 2 columns, something like this would work.  basically you just need to determine where the delimiter is, and then use the left and right functions to find the 2 pieces.
    declare @t table(value varchar(10))
    insert into @t(value)
    values
    ('ABC-12C4'), ('BC-A345'), ('CD'), ('XYZ')
    select
    case
    when charindex('-', value) != 0 then left(value, charindex('-', value) - 1)
    else value
    end as col1,
    case
    when charindex('-', value) != 0 then right(value, len(value) - charindex('-', value))
    else ''
    end as col2
    from @t

  • Convert rows to single column using t-sql

    Hi All,
    I have a table with 7 columns, et say..
      ID ,PatientName,Date,Time,Room_Num ,Specialized, DoctorName
    My source date looks like this..
      ID      PatientName     Date          Time    Room_Num  Specialized   DoctorName
       1         Sam        10/02/2010      10:00     4         Heart        
    John
       1         Sam        10/02/2010      10:00     4         Lungs        
    Harris
       2         Jones      11/12/2011      11:00     1         Lungs        
    Bob
       3         Jim        12/05/2001      01:00     2         Kidney       
    Greg
       3         Jim        12/05/2001      09:00     2         Eye          
    Roby
       1         Sam        12/22/2010      11:00     1         Heart        
    John
       1         Sam        12/22/2010      11:00     1         Lungs        
    Harris
    My out put should look like this..
       ID      PatientName     Date             DoctorName
       1         Sam        10/02/2010           John,Harris ( Need to be in 1 row because - ID, PatientName, Date is same)
       2         Jones      11/12/2011            Bob       ( Need to show as it is due to no repeatition
    of ID)
       3         Jim        12/05/2001            Greg,Roby   ( Need to be in 1 row because - ID, PatientName,
    Date is same)
       1         Sam        12/22/2010            John,Harris ( Need to be in 1 row because - ID, PatientName, Date is same)
    I am using below query to get above results but I am getting wrong results..Need some help in tweaking the query...
     SELECT DISTINCT ID ,PatientName , Date 
             ,STUFF(( SELECT ',' + DoctorName 
              FROM SampleTable ST1
              WHERE ST1.ID=ST2.ID
              FOR XML PATH('')),1,1,' ') AS DoctorName
              FROM SampleTable1 ST2
    GROUP BY ID ,PatientName , Date
    With above query I am getting results like this...
      ID      PatientName     Date             DoctorName
       1         Sam        10/02/2010         John,Harris ,John,Harris ( here John,Harris are repeating twice because of 4th row)
       2         Jones      11/12/2011         Bob      
       3         Jim        12/05/2001         Greg,Roby   
       1         Sam        12/22/2010         John,Harris ,John,Harris ( here John,Harris are repeating twice because of 1st row)
    Create table statement:
    Create table SampleTable
    ID Int null,     PatientName  varchar(25) null,   Date  datetime null,  Time varchar(10) null,   Room_Num int null, Specialized  varchar(20) null, DoctorName varchar(20) null
    Insert statement:
    Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam','10/02/2010' ,'10:00',4 ,'Heart','John')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1, 'Sam','10/02/2010' ,'10:00'   ,  4    ,     'Lungs','Harris')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 2, 'Jones' ,'11/12/2011'  ,    '11:00',1, 'Lungs',  'Bob')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values  ( 3,'Jim' ,'12/05/2001'    ,  '01:00',2,'Kidney' ,  'Greg')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 3,'Jim' ,'12/05/2001'     , '09:00',2,'Eye' ,   'Roby')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam' ,'12/22/2010'     , '11:00',1,'Heart', 'John')
     Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam', '12/22/2010'     , '11:00',1 , 'Lungs','Harris')
    I need help to tweak my query.
    Thanks,
    RH
    sql

    WITH cte AS(
    SELECT [ID]
    ,[PatientName]
    ,[Date]
    ,[Time]
    ,[Room_Num]
    ,[Specialized]
    ,[DoctorName]
    ,ROW_NUMBER() OVER(PARTITION BY [ID],[PatientName],[Date] ORDER BY Time) as RowID
    FROM [test].[dbo].[SampleTable]
    SELECT
    cte.[ID]
    ,cte.[PatientName]
    ,CAST(cte.[Date] as DATE) as [Date]
    ,STUFF((SELECT ',' + c.[DoctorName]
    FROM cte c
    WHERE c.ID=cte.ID AND c.PatientName=cte.[PatientName] AND c.[Date]=cte.[Date]
    FOR XML PATH(''),TYPE).value('.','varchar(max)')
    ,1,1,'') AS [DoctorName]
    FROM cte
    WHERE cte.RowID=1

  • Dynamically creating table and inserting rows and columns using JSP

    Hi,
    I'm using mysql and JSP to create web interface for my forms/tables. I wanna create the table dynamically depending on the data in the table and for each particualar record. and these values shud be loaded on the form after loading from the databaes as soon as the form loads.
    also i want to have a button which shud add new rows dynamically. and same one for columns.
    how do i calculate the values across the rows on the forms
    I'm new to JSP. Please point me in the right direction...any tutorials or code will be helpful.
    Any help is appreciated.
    Thanks
    Ayesha

    u write the code in sequence:
    1 write jdbs to select count(* )from table
    2 put in array e.g. String doc_no=new String[count];
    3 write jdbs to select * from table with condition
    //for no. of records just write
    for(int j=0;j<(count);j++){
    <% while(rs4.next()){
         doc_no=rs4.getString(2);
                        date1[i]=rs4.getString(3);
         doc_type[i]=rs4.getString(4);
         location[i]=rs4.getString(5);
         cheque[i]=rs4.getString(6);
         rate[i]=rs4.getInt(7);
         deb_qty[i]=rs4.getInt(8);
         cre_qty[i]=rs4.getInt(9);
         deb_amt[i]=rs4.getInt(10);
         cre_amt[i]=rs4.getInt(11);
         i++;
         //rs4.close();
                   for(int j=0;j<(count);j++){
                   System.out.println("Data count= "+j);
                   %>
    <tr>
    <td width="15%"><font size="1"><%=doc_no[j] %></font></td>
    <td width="10%"><font size="1"><%=date1[j] %></font></td>
    <td width="12%"><font size="1"><%=doc_type[j] %></font></td>
    <td width="9%"><font size="1"><%=location[j] %></font></td>
    <td width="9%">
    <div align="left"><font size="1"><%=cheque[j] %></font></div>
    </td>
    <td width="8%">
    <div align="right"><font size="1"><%=deb_qty[j] %></font></div>
    </td>
    <td width="8%">
    <div align="right"><font size="1"><%=cre_qty[j] %></font></div>
    </td>
    <td width="9%">
    <div align="right"><font size="1"><%=deb_amt[j] %></font></div>
    </td>
    <td width="10%">
    <div align="right"><font size="1"><%=cre_amt[j] %></font></div>
    </td>
    </tr>
    write if there is any specific problem
    bye,
    Samir

  • Same old question, but a little different I think

    I see that there are many, many questions about how to manage multiple computers and iPhones.  To be honest, the answers leave me a little confused, as I have tried a couple of the suggestions and nothing has helped my specific situation.  So I apologize if I'm being repetitive but please bear with me.
    Until recently we had one desktop with one version of iTunes that had everyone's songs on it (we're a family of 4).  In the last few months everyone has gotten iPhones, and my daughter just got a laptop, and this is where the confusion begins.  Everyone used the main iTunes account to sync up with their devices, then we started creating new accounts and nobody can get what they need anymore.
    It looks like currently all music and apps are on my wife's iTunes account.  The rest of us have some smaller subsets based on what we were authorized to load back onto iTunes (desktop) after loading stuff from my wife's iTunes account.  I think ideally what I would like to be able to do is have four separate iTunes accounts - each accessible from our individual desktop accounts (and my daughter's also from her laptop).  I'd like to be able to take all the songs and apps from the main account & dole them out to who they belong to, then have each of our devices linked to our own iTunes account.  So everything separate, BUT then I'd like to have the ability to share songs or apps between our accounts through directories when we want to.
    Does any of this make sense?  I don't know if our needs are realistic in general, if I need to back everything up and start from scratch, or how I do any of this.  I feel kind of dense that I can't figure this out.  Any help that can be offered would be greatly appreciated!
    Thanks!

    I use Handbrake (not available for Windows yet) or alternatively you could use quicktime pro
    800 MHz PowerPC G4   Mac OS X (10.4.4)   NEC DVD_RW ND-4550A - 30gb Ipod Video

  • Question about setting column width in SQL*Plus using info retrieved w SQL

    Good morning,
    Is there a way to tell SQL*Plus to set the width of a column to the greatest width of the elements found in the column ? (as opposed to the default which is the width declared in the DDL)
    In other words, I'd like to do something functionally equivalent to this:
    COL <columname> format a[select max(length(<columnname>)) from <thetablethatcontainscolumname>]
    I'm doing the above manually in two steps
    1. select max(length(columnname)) from .....
    2. col columnname format a[resultofstep1]
    Is there a way of doing it in one step ?
    Thank you for your help,
    John.

    Hi Munky,
    >
    you should consider whther you are using the correct tool for the job, SQLplus isn't exactly ideal for doing presentation layer stuff
    >
    I'm not really doing presentation stuff, I asked because it would be very convenient for everyday stuff. I commonly query the tables that I am going to deal withm just to have a look at the column names and a few values, something like:
    select * from EMP where rownum <= 10; -- just to have a look at the table and some values
    when the table contains a wide column then the display gets all messed up. It would be nice to have an option or a mechanism to tell SQL*Plus to automatically use the width of the widest value, instead of having to determine the value and then manually set the column.
    thank you for your help, it's good to know that I didn't miss some trivial setting in the documentation that would do it ;)
    John.

  • Editable fields (Rows and columns) using CL_SALV_HIERSEQ_TABLE

    Hi,
    I have to create an Hierarchical ALV with 2 Level using CL_SALV_HIERSEQ_TABLE.
    The problem is; i need check boxes as well as editable fields in column. I need checkboxes at item lines (which i am able to).
    Can anyone guide me how to make fields editable in CL_SALV_HIERSEQ_TABLE ?
    Thanks in advance.
    Regards,
    Hemant

    Editable fields(other than the checkboxes) are not supported using the ALV Object model(SALV classes).
    Regards,
    Rich Heilman

Maybe you are looking for

  • Outlook Integration: unable to create snapshot templates.

    Dear all, I followed all the steps mentioned in note 861055 "You can easily repeat the step of template creation after running the server installation:    1. Start the Addon Outlook Integration from Business one.    2. Choose/Administration/Outlook I

  • SQL results in ST05

    Hi, experts. I'm using ST05 to see how long a join is taking, but each time I trace it, I get a different value. Not a small difference, some times it's near 30.000 and other times near 2.000.000. What should I do to get a precisely result? Thanks in

  • Printer will not print goes to save the file xps documents

    Hello, My printer used to work fine but now as I try to print anything it sends me to Save the File as: Save In: My Pictures and has xps documents at the bottom. Can you help me, John

  • Extended with holding tax Remitence challan issue

    Dear Sapgurus, when i post J1INCHLN the transactions system will says one error message Business Place for document  could not be determined Message no. 8I707 Please guide me and i have maintain  J_1IEWTNUMGR_1 number groups for internal challan numb

  • Excluding records based on values

    Hi all; I have this datasource where there let's say there are several records with fields company code, costcenter, cost element, fiscal year, closing date etc. I need to select all records from that table excepts the ones which has the values on cl