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

Similar Messages

  • Convert rows to single column

    Hi All
    Need some assistance, i have a table where i want the output to be a single column
    ex: select from t1;*
    query output_
    rownum col_1
    1     8217
    2     6037
    3     5368
    4     5543
    5     5232
    i would like the result to be : *8217,6037,5368,5543,5232*
    thanks for your help in advance.
    i did look on the web but can't find a solution that is easily understood.

    Hi,
    855161 wrote:
    thanks for responding quickly.
    the link example seems not to work for me:
    below is the information you have requested:Below is some of what I requested. The CREATE TABLE and INSERT statements seem to be missing.
    1. duplicate values have no effect
    2. list doesn't need any order
    3. Version 10.2.0.5.0 For that, I recommend the user-defined aggregate function called STRING_AGG in the Oracle Base page, but called STRAGG by most of the people who use it. You have to copy and run about 60 lines of code from the Oracle Base page, or from AskTom one time, but once you have it installed, the job is as simple as
    SELECT  MIN (rnum)       AS rnum     -- ROWNUM isn't a good column name, since it's the same as a pseudo-column
    ,       STRAGG (count_1)  AS count_1_list
    FROM    table_x
    ;Hundreds of other jobs you have in the future will be just as easy, and you won't have to go through the installation process again.
    Relevant information:
    1. table columns : count_1
    all rows should become a single row with ',' in between
    example:
    select * from t1;
    output:
    Rownum count_1
    1 8217
    2 6037
    3 5368
    4 5543
    5 5232
    Desired results :
    Rownum count_1
    1 8217, 6037, 5368, 5543, 5232
    Edited by: 855161 on Dec 11, 2012 1:25 PMThe main problem with STRAGG is that it doesn't create a list in order. You said that's not an issue in this case, but if you ever do need output in order, then the best option in Oracle 10 is the SYS_CONNECT_BY_PATH technique. The main Oracle-Base page shows how to use SYS_CONNECT_BY_PATH in Oracle 9. Of course, that works in all later versions too, but in version 10 a simpler way, using CONNECT_BY_ISLEAF, became available. See the Oracle-Base Comments Page for the eaiser Oracle 10 technique.

  • Convert Rows  into single column

    Hi,
    My employee details table has data like below,
    employee_id position department
    100 technician 50
    100 IT 80
    101 Accountant 60
    101 Accounting Manager 70
    Now i want to covert the rows into column. So my output should be like this.
    output:
    employee_id position department position1 department1
    100 technician 50 IT 80
    101 Accountant 60 Accounting Manager 70
    Help me on this
    Edited by: Vi on Mar 22, 2012 5:36 AM
    Edited by: Vi on Mar 22, 2012 5:36 AM

    Igor.M wrote:
    http:// website link removed /t_converting_rows_columns.htm
    Please don't post links to commercial websites that are only trying to sell their products and services. It breaches the terms of use of the forums.
    There are usually more suitable websites giving much more valuable information without all the self promotion (google adwords etc. are acceptable), or in the case of this particular question there is a FAQ post that relates to it...
    {message:id=9360005}

  • How to convert rows into single columns in Oracle?

    I have table with data like shown below in Oracle database.
    P_COLUMN
    COLUMN_1
    COLUMN_2
    COLUMN_3
    COLUMN_ 4
    COLUMN_5
    COLUMN_6
    COLUMN_7
    COLUMN_8
    COLUMN_9
    COLUMN_10
    1
    A1
    A2
    A3
    A4
    A5
    A6
    A7
    A8
    A9
    A10
    1
    B1
    B2
    B3
    B4
    B5
    B6
    B7
    B8
    B9
    B10
    1
    C1
    C2
    C3
    C4
    C5
    C6
    C7
    C8
    C9
    C10
    2
    AA1
    AA2
    AA3
    AA4
    AA5
    AA6
    AA7
    AA8
    AA9
    AA10
    2
    BB1
    BB2
    BB3
    BB4
    BB5
    BB6
    BB7
    BB8
    BB9
    BB10
    I need a query to get one row based on P_COLUMN's value i.e. for P_COLUMN =1, below should be output :-
    C_1
    C_2
    C_3
    C_4
    C_5
    C_6
    C_7
    C_8
    C_9
    C_10
    C_11
    C_12
    C_13
    C_14
    C_15
    C_16
    C_17
    C_18
    C_19
    C_20
    C_21
    C_22
    C_23
    C_24
    C_25
    C_26
    C_27
    C_ 28
    C_29
    C_30
    C_31
    1
    A1
    A2
    A3
    A4
    A5
    A6
    A7
    A8
    A9
    A10
    B1
    B2
    B3
    B4
    B5
    B6
    B7
    B8
    B9
    B10
    C1
    C2
    C3
    C4
    C5
    C6
    C7
    C8
    C9
    C10
    2
    AA1
    AA2
    AA3
    AA4
    AA5
    AA6
    AA7
    AA8
    AA9
    AA10
    BB1
    BB2
    BB3
    BB4
    BB5
    BB6
    BB7
    BB8
    BB9
    BB10
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    i searched google and found PIVOT, CROSS JOIN etc but could not use those keyword properly.
    Thanks in advance.
    Note - My DB client version is 11g.

    Since you have 11G, here's an alternative with the PIVOT clause.
    First, set up test data with up to 10 rows:
    CREATE TABLE T(P1,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10) AS SELECT
    1,1,2,3,4,5,6,7,8,9,10 FROM DUAL;
    INSERT INTO T
    WITH DATA AS (SELECT LEVEL*10 N FROM DUAL CONNECT BY LEVEL <= 9)
    SELECT P1, C1+N, C2+N, C3+N, C4+N, C5+N, C6+N, C7+N, C8+N, C9+N, C10+N
    FROM T, DATA;
    INSERT INTO T
    SELECT P1+1,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10
    FROM T
    WHERE C1 <= 11;
    select * from t order by p1,c1;
    P1
    C1
    C2
    C3
    C4
    C5
    C6
    C7
    C8
    C9
    C10
    1
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    1
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    1
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    1
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    1
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    1
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    1
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    1
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    1
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    1
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    2
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    2
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    Now the SELECT statement using PIVOT:
    SELECT * FROM (
      SELECT T.*,
      ROW_NUMBER() OVER (
        PARTITION BY P1
        ORDER BY C1,C2,C3,C4,C5,C6,C7,C8,C9,C10
      ) RN
      FROM T
    PIVOT(
      MAX(C1) C1, MAX(C2) C2, MAX(C3) C3, MAX(C4) C4, MAX(C5) C5,
      MAX(C6) C6, MAX(C7) C7, MAX(C8) C8, MAX(C9) C9, MAX(C10) C10
      FOR RN IN (1 R1,2 R2,3 R3,4 R4,5 R5,6 R6,7 R7,8 R8,9 R9,10 R10)
    P1
    R1_C1
    R1_C2
    R1_C3
    R1_C4
    R1_C5
    R1_C6
    R1_C7
    R1_C8
    R1_C9
    R1_C10
    R2_C1
    R2_C2
    R2_C3
    R2_C4
    R2_C5
    R2_C6
    R2_C7
    R2_C8
    R2_C9
    R2_C10
    R3_C1
    R3_C2
    R3_C3
    R3_C4
    R3_C5
    R3_C6
    R3_C7
    R3_C8
    R3_C9
    R3_C10
    R4_C1
    R4_C2
    R4_C3
    R4_C4
    R4_C5
    R4_C6
    R4_C7
    R4_C8
    R4_C9
    R4_C10
    R5_C1
    R5_C2
    R5_C3
    R5_C4
    R5_C5
    R5_C6
    R5_C7
    R5_C8
    R5_C9
    R5_C10
    R6_C1
    R6_C2
    R6_C3
    R6_C4
    R6_C5
    R6_C6
    R6_C7
    R6_C8
    R6_C9
    R6_C10
    R7_C1
    R7_C2
    R7_C3
    R7_C4
    R7_C5
    R7_C6
    R7_C7
    R7_C8
    R7_C9
    R7_C10
    R8_C1
    R8_C2
    R8_C3
    R8_C4
    R8_C5
    R8_C6
    R8_C7
    R8_C8
    R8_C9
    R8_C10
    R9_C1
    R9_C2
    R9_C3
    R9_C4
    R9_C5
    R9_C6
    R9_C7
    R9_C8
    R9_C9
    R9_C10
    R10_C1
    R10_C2
    R10_C3
    R10_C4
    R10_C5
    R10_C6
    R10_C7
    R10_C8
    R10_C9
    R10_C10
    1
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    2
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

  • 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.

  • Convert different rows into single column

    DB : 11.1.0.7
    OS : Solaris Sparc 5.10
    I have one query which is joining few tables and giving me output like below.
    personnum orgnm
    ======= =======
    6     Keyholder
    9     Sales
    3     Mgmt
    I would like to convert that into single column like below.
    col1
    ========
    6,Keyholder,9,Sales,3,Mgmt
    I have tried with pivot and decode, but not getting resule which I am exepcting. Any suggesstions ?

    yashwanth437 wrote:
    listagg() function could work.LISTAGG is not available in 11.1. It was introduced in 11.2.
    Anyway, XML solution:
    with sample_table as (
                          select 6 personnum,'Keyholder' orgnm from dual union all
                          select 9,'Sales' from dual union all
                          select 3,'Mgmt' from dual
    select  rtrim(xmlagg(xmlelement(e,personnum || ',' || orgnm,',').extract('//text()')),',') col1
      from  sample_table
    COL1
    6,Keyholder,9,Sales,3,Mgmt
    SQL> SY.

  • How to remove dotted lines in a single column using javascript?

    Hi,
    In InDesign document,i want to remove the dotted lines in a single column using javascript.here i want to remove only the dotted lines has presented at the end of text in a cell.kindly help me if anyone has idea regarding this.
    Thanks in advance!
    Vimala L

    Hi,
    Those dotted lines have added in the document by manually. The dotted lines have presented in all the columns but in a single column i need to remove it.
    Thanks,
    Vimala L

  • How to Splilit The String Into Single Column using Comma As Delimiter ?

    How to Splilit The String Into Single Column using Comma As Delimiter ?
    using Function

    refer my thread ,code is also available see if that helps you
    error while executing the sp ORA-21779: duration not active

  • 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

  • Display two heading in single column using ALV report

    Hi Experts,
    I got a requirement for displaying 2 rows heading in a single column report. Is it possible that I can perform this task using ALV. How to get this 2 rows in ALV.
    This is a criteria that need to be output in ALV REPORT.
    MATERIAL CODE--MATERIAL NUMBERSTORAGE LOC----SLOC1     SLOC2
    --DATE--DATE1      DATE2
    123445--TEST MATERIAL22--
    3
    As mentioned above storage loc and date will be changing with respect to data dynamically and under this double heading qty will be displayed.
    Just want to know how to get double heading. It is clear that how to display dynamically but unaware of double heading using fieldcatalog.
    Regards,
    Yahya

    Hi Yahya,
    Please pass row position in fieldcatalogue for the respective columns.
    E.g  MOVE '2' to w_fieldcat-row_pos.  " This will display the field in 2nd row.
    Thanks,
    Rupali

  • Displaying Document Name With The Summary in a Single Column Using Document Library View.

    Hi All,
    I have a question that relates to SharePoint Document Library Views. I want to view the Documents name with the summary in a single column. Below image shows an example of it. I need this within a SharePoint Document Library. Also I want the height of the
    row to be increased more than the default height. I cannot figure it out how to do that? Could you someone help me to do this. I have inserted the Document Library as an App Part to the page. 
    So could you someone help me to solve this matter?
    Thanks and regards,
    Chiranthaka

    HI Chiranthaka,
    You can create DataView webpart using SPD and then modify the display template according to your need.
    http://deannaschneider.wordpress.com/2012/07/10/item-counts-dvwp-sp2010/
    Hope this will help to solve your problem.
    Best Regards,
    Brij K

  • Displaying Document Name & The Summary in a Single Column Using Document Library View

    Hi All,
    I have a question that relates to SharePoint Document Library Views. I want to view the Documents name with the summary in a single column. Below image shows an example of it. I need this within a SharePoint Document Library. Also I want the height of the row
    to be increased more than the default height. I cannot figure it out how to do that? Could you someone help me to do this. I have inserted the Document Library as an App Part to the page. 
    So could you someone help me to solve this matter?
    Thanks and regards,
    Chiranthaka

    HI Chiranthaka,
    You can create DataView webpart using SPD and then modify the display template according to your need.
    http://deannaschneider.wordpress.com/2012/07/10/item-counts-dvwp-sp2010/
    Hope this will help to solve your problem.
    Best Regards,
    Brij K

  • Displaying 2 columns in a single column using HTML section of reports.

    Hi Team,
    I have a requirement in which we need to display 2 columns in the same column of OBIEE report. At present we have 2 columns as 2 different columns.
    For example if i have a column A which is used as @A in html section i need the new column to have @A + @B where B is another column in database.
    Can i concatenate 2 columns in a single column ?
    Thanks,
    Ritesh

    first select column 1 and column 2 in criteria.
    go to reaults are add narrater view.
    in narrater view type.
    @1@2[br/]
    set number of rows
    this should work in narrator.
    Edited by: user10615659 on May 20, 2013 4:30 PM

  • How to join 2 rows under single column header

    i want to join 2 or more rows under a single column header. as shown "container details" is the column name with "h", "w", and "s" and the sub column names. so my header should contain all these four names and my 3 rows under h,w and s should be clubed under this container details.
    anyone help me out. thanks in advance.
    container details
    | h | w | s

    Bummer, I just tried the link (which I saved from a couple months ago) and it doesn't work. This was a great site for showing how to do various things in Swing. Sorry for the bad link. Maybe someone saved the sites info or knows where it may have moved. Dang...

  • 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;

Maybe you are looking for