按照ID分组,把content的内容合并起来(中间加上","),结果如下:
ID content
1 aa,dd
2 bb,ee
3 cc,ff
用一句SQL怎么写??
我想到 select ?? from table group by ID,关键是??怎么写呢??
...全文
1107打赏收藏
求一SQL语句的写法,不难,谢谢帮忙.
ID content 1 aa 2 bb 3 cc 1 dd 2 ee 3 ff 按照ID分组,把content的内容合并起来(中间加上","),结果如下: ID content 1 aa,dd 2 bb,ee 3 cc,ff 用一句SQL怎么写?? 我想到 select ?? from table group by ID,关键是??怎么写呢??
create function f1(@a int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+','+content from table1 where id=@a
return(stuff(@r,1,1,''))
end
go
--调用实现查询
select id,content=dbo.f1(id) from table1 group by id
--生成测试数据
create table t(ID int,content varchar(20))
insert into t select 1,'aa'
insert into t select 2,'bb'
insert into t select 3,'cc'
insert into t select 1,'dd'
insert into t select 2,'ee'
insert into t select 3,'ff'
go
--创建用户定义函数
create function f_str(@ID int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret + ',' + content from t where id=@id
set @ret = stuff(@ret,1,1,'')
return @ret
end
go
--执行查询
select ID,content=dbo.f_str(ID) from t group by ID