【问题标题】:rolling up multiple rows in a single row in a colum order in sql server在sql server中按列顺序在单行中汇总多行
【发布时间】:2019-09-11 14:06:59
【问题描述】:

如何将具有相同值的多行以逗号分隔并按升序组合在单列中(在 SQL Server 中)返回到单行中?

表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

【问题讨论】:

  • 您使用的是哪个 RDMS?而且看起来您使用的不是表 2?
  • 现在我想更清楚了,我已经更新了问题:)
  • 你的 rdbms 是什么? Sql Server、postgres、oracle?什么版本?
  • rdbms 是 SQL server

标签: sql sql-server string-aggregation


【解决方案1】:

希望这是您正在寻找的:

select Col1, string_agg(Col2, ',') within group(order by Col3)
from Table2
group by Col1

【讨论】:

  • @SQL_NewUser 它对我有用。也许您想要 desc 排序顺序,在这种情况下您可以进行以下更改(按 Col3 desc 排序)。
猜你喜欢
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2014-08-15
相关资源
最近更新 更多