SQL Query to get aggregated result in comma separators along with group by column in SQL Server(SQL Query 以逗号分隔符以及 SQL Server 中的按列分组获取聚合结果)

本文介绍了SQL Query 以逗号分隔符以及 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功能是去掉前面的', '.

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

You can also see another examples here:

  • SQL 两个之间的相同单元表格需要 1 个单元格中的订单号
  • SQL 和 Coldfusion 左连接表在一列中以列表形式获得重复结果

这篇关于SQL Query 以逗号分隔符以及 SQL Server 中的按列分组获取聚合结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!