一个简单的sql分组合并字段
----------------------------------创建表添加数据-------------------------------
if object_id('tb') is not null
drop table tb
go
create table tb(id int, [value] varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
select a.id,
[valus]=stuff((select '/'+value from tb where id=a.id for xml path('')),1,1,'')
from tb a
----------------------------------创建表添加数据-------------------------------
if object_id('tb') is not null
drop table tb
go
create table tb(id int, [value] varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
-----------------------------------查询语句--------------------------------------
select a.id,
[valus]=stuff((select '/'+value from tb where id=a.id for xml path('')),1,1,'')
from tb a
group by a.id
如下图:

本文介绍了一种使用SQL实现的简单方法来将同一记录ID下的多个字段值进行合并,并通过stuff与for xml path函数组合使用的方式展示如何形成带有分隔符的单一字符串输出。
1227

被折叠的 条评论
为什么被折叠?



