sql中怎样把同一张表中相同字段的内容合并为一条记录(不同字段的那一列每个记录后面加逗号)

一、创建表

create table stuUnion
(
 sid int identity primary key,
 cid int,
 id varchar(500)
)

 

二、添加数据

insert into stuUnion
select 1,'a' union
select 1,'b' union
select 2,'c' union
select 2,'d' union
select 3,'e' union
select 3,'f' union
select 3,'g'

 

三1、用标量函数查询

(1)创建标量函数

create function b(@cid int)
returns varchar(500)
as
begin
declare @s varchar(500)
select @s=isnull(@s+'','')+rtrim(id)+',' from stuUnion where cid=@cid
return @s
end;

 

(2)用标量函数查询

select cid,dbo.b(cid) as id from stuUnion group by cid

 

三2、用sqlserver的xml

select cid,ID=STUFF((select ' '+rtrim(id)+',' from stuUnion where st.cid=cid order by id for XML path('')),1,1,'') from stuUnion st group by cid

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值