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

Similar Messages

  • 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 columns with decode function

    Hi,
    How to convert rows into columns with the help of decode function in oracle.
    thanks and regards
    P Prakash

    say
    col1 col2
    1 10
    2 20
    3 30
    then use
    select col1,
    sum(decode(col2,10,10)) "new1"
    sum(decode(col2,20,20))"new2"
    sum(decode(col2,30,30))"new3"
    from table_name
    group by col1;
    we used sum u can use ny function if wont u have to give the column name i.e col2 name also
    so i think u got it nw
    regards

  • How to convert rows into column

    Hi,
    can any one help me how to convert rows into column by pl/sql procedure.
    Thanks and Regards

    http://www.oracle.com/technology/oramag/code/tips2004/050304.html
    -- dropping the sample table if exists
    drop table rowstocol
    -- create sample table
    create table rowstocol ( name varchar2(20));
    -- Inserting rows into sample table
    insert into rowstocol values('Amit Zhankar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Ashish Ghelani');
    insert into rowstocol values('Aditi Zhankar');
    insert into rowstocol values('Tom Kyte');
    insert into rowstocol values('Oracle');
    -- Following query should be run to create a sql. This result sql should be run to convert rows to column.
    -- The following query uses just the tablename (whose data is to be converted) and name of the column (which is to be converted).
    -- Example taken here is table rowstocol, column name.
    SELECT cc
    FROM (select decode(rn ,1 ,'Select ',null) ||' MAX (CASE WHEN dr = '|| rownum||' THEN DECODE (rn,1, col1) END) '||
    decode(rn,maxr,' col1 from ','||'||chr(39)||','||chr(39)||'|| ') cc,rn,maxr
    from (SELECT ROWNUM rn,count(0) over() maxr FROM rowstocol) order by rn) trows
    union all
    select '(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn' cc from dual;
    -- The result of this query will do the reqd conversion from row to column.
    -- Replace table rowstocol by your table, column name by your column.
    CC
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn;
    COL1
    Aditi Zhankar,Amit Zhankar,Ashish Ghelani,Oracle,Oracle,Piyu Yawalkar,Piyu Yawalkar,Tom Kyte
    Edited by: bhooma on Jan 20, 2009 2:44 AM

  • How to convert rows into columns

    Hi,
    How to convert rows into columns of two different tables.
    These two tables have two common columns namely (shipline,pos).
    Let me know if we have any built in functions to do this.
    thank you very much .
    Edited by: 808542 on Dec 7, 2010 8:35 PM
    Edited by: 808542 on Dec 7, 2010 8:37 PM

    Have you tried this first?
    http://forums.oracle.com/forums/search.jspa?threadID=&q=row+to+column&objID=f75&dateRange=last90days&userID=&numResults=15&rankBy=10001

  • 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 convert row into column

    Hi All,
    My oracle apps version is r12 and db is 10 and i am using Bi publisher version 10g.
    Is it possible to convert row into column in Rtf template,
    My Query is
    SELECT distinct pvs.vendor_site_code,sum(aia.invoice_amount)
    FROM ap_invoices_all aia, po_vendors po, po_vendor_sites_all pvs
    WHERE aia.org_id = pvs.org_id
    AND aia.vendor_id = po.vendor_id
    AND aia.vendor_site_id = pvs.vendor_site_id
    AND aia.org_id=204
    group by pvs.vendor_site_code
    And output is like this
    Vendor sitecode Invoiceamt
    EAM-ERS 79240
    STAR GATE - PAY 3245902.31
    UPS - HQ 10792040.9
    Like this
    So in template i need the output like this
    Vendor sitecode EAM-ERS STAR GATE - PAY UPS - HQ
    Invoiceamt 79240 3245902.31 10792040.9
    I tried to achieve the output using sql query but by hardcoding only i have achieved it, so i have tried to convert directly in RTF template.
    can any one tell me is it possible.
    And if new project is added from the front end ie(now the query will produce 4 rows but now in template i have created only three columns)
    Is it possible to add a new column dynamically.
    Can any one please guide me and tell me is there any example.
    Thanks & regards
    Srikkanth

    Take a look at this post: http://blogs.oracle.com/roller-ui/bsc/spider.jsp?entry=MT%3aENTRY%3a5001
    Thanks,
    Bipuser

  • Converting multiple column rows into single column

    Hi all Below is my requirement, can you anybody help me solve it. CREATE TABLE TYPE (   c1_type  VARCHAR2 (10),   c2_type  VARCHAR2 (10),   c3_type  VARCHAR2 (10),   c4_type  VARCHAR2 (10),   c5_type  VARCHAR2 (10),   c6_type  VARCHAR2 (10),   c7_type  VARCHAR2 (10),   c8_type  VARCHAR2 (10),   c9_type  VARCHAR2 (10)); INSERT INTO TYPE     VALUES ('Region_D',             'Region_E',             'Region_F',             'Region_D',             'Region_E',             'Region_D',             'Region_M',             'Region_D',             'Region_E'); commit; Acutal output on the below query select * from type; C1_TYPE C2_TYPE C3_TYPE C4_TYPE C5_TYPE C6_TYPE C7_TYPE C8_TYPE C9_TYPE Region_D Region_E Region_F Region_D Region_E Region_D Region_M Region_D Region_E Acutal i am expecting the below output,how to make it using query or using oracle built in function. Region_D Region_D Region_D Region_D Region_E Region_E Region_E Region_F Region_M

    Hi,
    So, you want to put the column values in alphabetic order, with the earliest value in c1_type and the last in c9_type, is that it?
    The fact that you even want to do this says that this is a bad table design.  If sorting the values makes sense, then putting them all in the same column on 9 different rows (rather than 9 different columns on 1 row) makes sense.
    If you're stuck with the current design, then use SELECT ... UNPIVOT to put them on separate rows, then use the analytic ROW_NUMBER function to assign numbers 1-9 to each value, and finally use SELECT ... PIVOT to put them back into 1 row in that order.  If you're not familiar with the built-in UNPIVOT and PIVOT features, look them up in the SQL Language manual, and see the forum FAQ:
    https://forums.oracle.com/message/9362005
    If you get stuck, post your best attempt (formatted), the exact results you want (formatted), and your Oracle version (e.g. 11.2.0.2.0).
    Also, TYPE is an Oracle keyword, so it's not a good table name.  Use something like location_type instead.

  • Hiii, i have m rows & n columns in my table..how to convert it into m columns & n rowa by using sql..pls help me...thanks.

    hiii,
    I have a table which has 14 rows & 8 cols.
    I want covert it into 14 cols & 8 rows,
    by using sql how to do it..pls help me.

    Oracle Database Search Results: pivot

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

  • How to transpose rows into multiple columns using pivot table

    I have 1 row containing 12 columns with value "JAN", "FEB", "MAR", "J-1","F-1","M-1","J-2","F-2","M-2","J-3","F-3","M-3"
    I want to display as
    JAN J-1 F-1 M-1
    FEB J-2 F-2 M-2
    MAR J-3 F-3 M-3
    How do I achieve the above?

    Today you have only 3 months JAN, FEB, MAR. Is it always the same number of columns. What if there are more months added to this row?
    Is your data really coming from relational source or some sort of text file?
    There is a better way to do this in narrative view using HTML if your requirement is just to show them in multiple rows and do some calculations.
    Go to Narrative View;
    In prefix, use <html> <table>
    In 'Narrative' text box add something like this
    <tr> <td> @1 </td> <td> @4 </td> <td> @7 </td> </tr>
    <tr> <td> @2 </td> <td> @5 </td> <td> @8 </td> </tr>
    <tr> <td> @3 </td> <td> @6 </td> <td> @9 </td> </tr>
    In Suffix, use </table> </html>
    You can also add simple calculations like sum etc at the very bottom of these rows as grand totals.
    kris

  • How to convert rows into columns in sql server?

    Hi All,
    I have table called table1 which contains the below information
    Projectname           Weeks       Work
    p1                          w5            200
    p1                          w6            300
    p1                          w7            234
    p2                          w5            765
    p2                          w6            987
    p3                          w1            976
    p3                          w2            231
    I need to pivot this table. I need the info like below
    Projectname          w1        w2          w5          w6       
    w7
    p1                                                  
    200        300        234
    p2                                                  
    765         987
    p3                        976       231
    How can I make like this?

    One more way,
    create table #temp(Projectname varchar(10),Weeks varchar(10), Work int)
    insert into #temp values('p1','w5',200)
    insert into #temp values('p1','w6',300)
    insert into #temp values('p1','w7',234)
    insert into #temp values('p2','w5',765)
    insert into #temp values('p2','w6',987)
    insert into #temp values('p3','w1',976)
    insert into #temp values('p3','w2',231)
    Select ProjectName,
    Sum(Case when Weeks = 'W1' Then Work Else NULL End) W1,
    Sum(Case when Weeks = 'W2' Then Work Else NULL End) W2,
    Sum(Case when Weeks = 'W3' Then Work Else NULL End) W3,
    Sum(Case when Weeks = 'W4' Then Work Else NULL End) W4,
    Sum(Case when Weeks = 'W5' Then Work Else NULL End) W5,
    Sum(Case when Weeks = 'W6' Then Work Else NULL End) W6,
    Sum(Case when Weeks = 'W7' Then Work Else NULL End) W7
    From #temp
    Group by ProjectName
    Drop table #temp

  • How to convert Rows to different columns

    Hi All,
    I am having a table address with the following data.
    ID          REL_NAME     REL_RELATION  REL_PHONE
    1---          kish_rel1---     wife---     1111
    1---          kish_rel2---     sister---     2222
    1---          kish_rel3---     brother---     3333
    2---          ram_rel1---     brother---     4444
    Now i want to display rows data into columns. See the output i want. Exactly, I dont know how many rows are there for each ID. It may increase or decrease.
    ID          REL_NAME     REL_RELATION  REL_PHONE
    1---kish_rel1---     wife---     1111---kish_rel2---     sister---     2222---kish_rel3---     brother---     3333
    2---ram_rel1---     brother---     4444
    Thanks in advance,
    Pal

    Hi,
    I have found this is useful. But it is static. It wont work if we dont know the maximum number of rows present when grouped by ID.
    Is there any other solution, which will give correct values, if we dont know the row count when grouped by ID.
    SELECT hrid,
    MAX(case when seq=1 then rel_name end) AS "rel_name1",
    MAX(case when seq=1 then rel_relation end) AS "rel_relation1",
    MAX(case when seq=1 then rel_phone end) AS "rel_phone1",
    MAX(case when seq=2 then rel_name end) AS "rel_name2",
    MAX(case when seq=2 then rel_relation end) AS "rel_relation2",
    MAX(case when seq=2 then rel_phone end) AS "rel_phone2",
    MAX(case when seq=3 then rel_name end) AS "rel_name3",
    MAX(case when seq=3 then rel_relation end) AS "rel_relation3",
    MAX(case when seq=3 then rel_phone end) AS "rel_phone3",
    MAX(case when seq=4 then rel_name end) AS "rel_name4",
    MAX(case when seq=4 then rel_relation end) AS "rel_relation4",
    MAX(case when seq=4 then rel_phone end) AS "rel_phone4"
    FROM (SELECT hrid, rel_name, rel_relation, rel_phone, ROW_NUMBER() over(partition by hrid ORDER BY hrid) AS seq FROM address)
    GROUP BY hrid
    Thanks,
    Pal

  • 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

  • How to Convert Rows of the Columns in Multiple Columns

    Hi,
    I have Data in one of the table of Oracle Application.
    Sample Data.....
    Period_Start_date Period_Type Demand
    09-22-2005 1 5
    09-21-2005 1 10
    09-20-2005 1 5
    09-19-2005 1 2
    09-18-2005 1 20
    09-17-2005 1 19
    09-16-2005 1 3
    Output Required.
    Period 6 Period 5 Period 4 Period 3 Period 2 Period 1 Current
    3 19 20 2 5 10 5
    This need to be Done in Using SQL Statement.
    On the base of Current Date enter by the User ...it will pickup last six date and Demand on that Date in Required Format.
    Pls Do let me know Any more Clarification
    Pls can any body Help me
    Regards
    Roshan

    CREATE TABLE t1
    ( col1 VARCHAR2(10),
    col2 VARCHAR2(100)
    INSERT INTO t1 VALUES('A','123,456,789');
    INSERT INTO t1 VALUES('B','012,345');
    INSERT INTO t1 VALUES('C','678,901,234');
    SELECT col1, col2, pos, pre, SUBSTR(col2, pre+1, pos-pre-1) token FROM (
    SELECT row_num, col1, col2, decode(pos,0,LENGTH(col2)+1,pos) pos, pre FROM (
    SELECT row_num, col1, col2, pos, nvl(LAG(pos) OVER (PARTITION BY col1 ORDER BY row_num),0) pre
    FROM (
    SELECT row_num, vw.col1, vw.col2, INSTR(vw.col2,',',1,row_num) pos
    FROM (
    SELECT ROWNUM row_num FROM (
    SELECT LEVEL FROM dual connect by LEVEL <= 5
    )) r,
    (SELECT col1, col2 FROM t1) vw
    WHERE pos <> 0 OR pre <> 0
    i think some part it may be help u also

Maybe you are looking for