How to combine multiple rows in MSSQL(如何在 MSSQL 中合并多行)
问题描述
可能的重复:
在MS SQL Server 2005中模拟group_concat MySQL函数?一个>
SQL Server 中的连接组
我正在尝试编写一个将行组合在一起的 SQL 查询.我需要它按 ID# 将未指定数量的行组合在一起,但将它们的地址连接到一个单元格中.
I am trying to write an SQL query that will combine rows together. I need it to group together an unspecified number of rows by ID# but concatenate their addresses let's say into one cell.
说我们有
ID, Address
p1 a1
p1 a2
p1 a3
p2 a4
p2 a5
我想得到
ID, Address
p1 a1,a2,a3
p2 a4,a5
每个 ID 的地址数量可能会有所不同.有些 ID 为 1,有些则为 50.
The number of addresses per ID can vary. Some IDs have 1, others can have 50.
任何帮助将不胜感激.提前致谢!
Any help would be appreciated. Thanks in advance!
推荐答案
Select T1.Id
, Stuff(
(
Select ', ' + T2.Address
From MyTable As T2
Where T2.Id = T1.Id
Order By T2.Address
For Xml Path(''), type
).value('.', 'nvarchar(max)'), 1, 2, '') As Address
From MyTable As T1
Group By T1.Id
这篇关于如何在 MSSQL 中合并多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MSSQL 中合并多行


基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01