SQL Query to get aggregated result in comma separators along with group by column in 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 中的按列分组获取聚合结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Query 以逗号分隔符以及 SQL Server 中的按列分组获取聚合结果
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在多列上分布任意行 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
