如何写sql语句让相同的id的content合并

肥胖的柠檬 2006-10-31 01:29:45
各位,征答案:
ID COTENT
--------------------
1 , "aaa"
1 , "bbb"
1 , "ccc"
2 , "aa "
2 , "bb"
如何写sql语句让相同的id的content合并

就是结果变成
ID Cotent
-------------------------
1 ,"aaabbbccc"
2 ,"aabb"
...全文
128 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
OracleRoob 2006-10-31
  • 打赏
  • 举报
回复
/*
有表tb, 如下:
id txt
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc

需要得到结果:
id values
------ -----------
1 aa,bb
2 aaa,bbb,ccc

即: group by id, 求 txt 的和(字符串相加)
*/

create table tb(id int,txt varchar(100))
go
insert into tb
select 1,'aaa' union all
select 1,'bbb' union all
select 2,'ccc' union all
select 3,'ddd' union all
select 3,'eee' union all
select 3,'fff'

go
--写一个聚合函数:
create function dbo.fn_Merge(@id int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+';'+txt from tb where id=@id
return stuff(@r,1,1,'')
end
go

-- 调用函数
select id, dbo.fn_Merge(id) as txt from tb group by id

go
drop table tb
drop function fn_Merge
九斤半 2006-10-31
  • 打赏
  • 举报
回复
用函数,参考:

--测试数据
create table csdn(id int,txt varchar(10))
insert csdn
select 1,'a' union all
select 1,'b' union all
select 1,'c' union all
select 2,'aa' union all
select 2,'bb' union all
select 2,'cc' union all
select 3,'aaa' union all
select 3,'bbb'
select * from csdn
go

create function Gettxt(@id int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s +',' +txt from csdn where id=@id
--return @s
return stuff(@s,1,1,'')
end
go

select id,dbo.Gettxt(id) txt from csdn group by id
go

drop function Gettxt
drop table csdn
go

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧