SQL 查询以逗号分隔符以及 SQL Server 中的按列分组获取聚合结果

我需要在表上编写一个 sql 查询,以便结果将包含按列分组以及带逗号分隔符的聚合列.

I need to write a sql query on the table such that the result would have the group by column along with the aggregated column with comma separators.

我的表格将采用以下格式

My table would be in the below format

   |`````````|````````|
   |    ID   |  Value |
   |_________|________|
   |    1    |   a    |
   |_________|________|
   |    1    |   b    |
   |_________|________|
   |    2    |   c    |
   |_________|________|

预期结果应为以下格式

   |`````````|````````|
   |    ID   |  Value |
   |_________|________|
   |    1    |  a,b   |
   |_________|________|
   |    2    |   c    |
   |_________|________|

推荐答案

您想使用 FOR XML PATH 构造:

select 
    ID, 
    stuff((select ', ' + Value 
           from YourTable t2 where t1.ID = t2.ID 
           for xml path('')),
          1,2,'') [Values]
from YourTable t1
group by ID

STUFF 的作用是去掉前面的', '.

The STUFF function is to get rid of the leading ', '.

您还可以在此处查看其他示例:

You can also see another examples here:

  • 两个SQL相同的单元表格需要 1 个单元格中的订单号
  • SQL 和 Coldfusion 左连接表获得重复结果作为一列中的列表

相关文章