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

查看:48
本文介绍了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 查询以逗号分隔符以及 SQL Server 中的按列分组获取聚合结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆