在 sql 服务器中按列顺序将多行汇总为单行
rolling up multiple rows in a single row in a colum order in sql server
我怎样才能 return 将具有相同值的多行以逗号分隔并按升序组合在单个列中的单行中(在 SQL 服务器中)?
表2
------------
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
根据 col3 升序排列的所需结果:
Col1 | col2
----------------------------
1 | Line2,Line1,Line3
2 | Line4,Line6,Line5
3 | Line8,Line7
希望这就是您要找的:
select Col1, string_agg(Col2, ',') within group(order by Col3)
from Table2
group by Col1
我怎样才能 return 将具有相同值的多行以逗号分隔并按升序组合在单个列中的单行中(在 SQL 服务器中)?
表2
------------
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
根据 col3 升序排列的所需结果:
Col1 | col2
----------------------------
1 | Line2,Line1,Line3
2 | Line4,Line6,Line5
3 | Line8,Line7
希望这就是您要找的:
select Col1, string_agg(Col2, ',') within group(order by Col3)
from Table2
group by Col1