我需要在表上编写一个 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 中的按列分组获取聚合结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!