Monday, 12 February 2018

How to display multiple rows in one records in sql

Syntax :
select
   Col1,
        listagg(COL2, ',') within group (order by COL2) as COL2
From TABLE
Group By
   Col1


Example
Create Table Test_Transpose(Ids Number , Val Number);
Insert Into Test_Transpose Values (1, 11);
Insert Into Test_Transpose Values (1, 12);
Insert Into Test_Transpose Values (1, 13);
Insert Into Test_Transpose Values (1, 14);
Insert Into Test_Transpose Values (1, 15);
Insert Into Test_Transpose Values (2, 21);
Insert Into Test_Transpose Values (2, 22);
Insert Into Test_Transpose Values (2, 23);
Insert Into Test_Transpose Values (2, 24);
Insert Into Test_Transpose Values (2, 25);
Commit;
/

Select * From  Test_Transpose;
Output

IDS VAL
1 11
1 12
1 13
1 14
1 15
2 21
2 22
2 23
2 24
2 25

Select
   IDS,
        listagg(VAL, ',') within group (order by VAL) as VAL
From Test_Transpose
Group By
   Ids

Output :


IDS VAL
1 11,12,13,14,15
2 21,22,23,24,25

No comments:

Post a Comment