0

How can I return multiple rows with the same values into a single row as comma separated and combined in ascendant order in a single column (in SQL server)?

Table2

------------
col1 | col2 | col3
----------------------
1    | line1 | 2
1    | line2 | 1
1    | line3 | 4
2    | line4 | 1
2    | line5 | 3
2    | line6 | 2  
3    | line7 | 2
3    | line8 | 1

Desired result in ascendant order according to col3:

Col1 |  col2
----------------------------
1    | Line2,Line1,Line3
2    | Line4,Line6,Line5
3    | Line8,Line7
db_noob
  • 119
  • 2
  • 11

1 Answers1

1

Hopefully this is what you are looking for:

select Col1, string_agg(Col2, ',') within group(order by Col3)
from Table2
group by Col1
Neeraj Agarwal
  • 1,059
  • 6
  • 5
  • @SQL_NewUser It is working for me. Maybe you want desc sort order, in which case you can make the following change (order by Col3 desc). – Neeraj Agarwal Sep 11 '19 at 16:48