字符串+ 聚合函数? 帮忙写个SQL语句,或者给予一个解决方法,
存在一个表
表名:t_example
字段:meetingid, joiner
类型:varchar(10), varchar(10)
数据:1000 李梅
1000 王俊
1000 张风
1001 哗啦啦
1001 王俊
想要的输出结果是:
1000 李梅王俊张风
1001 哗啦啦王俊
这样子最好了:
1000 李梅,王俊,张风
1001 哗啦啦,王俊
应该怎么做呢??
------解决方案--------------------declare function fun_test(@cid varchar(2000))
returns varchar(2000)
as
begin
declare @chr varchar(2000)
set @chr= ' '
select @chr=@chr+joiner+ ', ' from 表 where meetingid=@cid
return @chr
end
select distinct meetingid,dbo.fun_test(meetingid) from 表
------解决方案--------------------create table t_example(meetingid varchar(10),joiner varchar(10))
insert t_example select '1000 ', '李梅 '
union all select '1000 ', '王俊 '
union all select '1000 ', '张风 '
union all select '1001 ', '哗啦啦 '
union all select '1001 ', '王俊 '
--写一个聚合函数:
create function dbo.fn_Merge(@meetingid varchar(1000))
returns varchar(8000)
as
begin
declare @name varchar(8000)
set @name= ' '
select @name=@name+ ', '+joiner from t_example where meetingid=@meetingid
return stuff(@name,1,1, ' ')
end
go
-- 调用函数
select meetingid, dbo.fn_Merge(meetingid) from t_example group by meetingid
------解决方案-------------------- create table t(meetingid int,joiner varchar(100))
insert into T select 1000, '李梅 '
insert into T select 1000, '王俊 '
insert into T select 1000, '张风 '
insert into T select 1001, '哗啦啦 '
insert into T select 1001, '王俊 '
select * from T
go
--写一个聚合函数:
create function dbo.fn_Merge(@id int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+ '; '+joiner from T where meetingid=@id
return stuff(@r,1,1, ' ')
end
go
-- 调用函数
select meetingid, dbo.fn_Merge(meetingid) as joiner from T group by meetingid
go
drop function fn_Merge
drop table T