请教一个SQL语句,希望大家都来帮帮忙
--C
CID CName
1 张三
2 李四
3 王五
4 赵六
--J
JID CID JName
1 1 A
2 1 B
3 3 A
4 2 W
5 4 G
6 1 V
7 1 X
我想得到
1 张三 A,B,V
2 李四 W
3 王五 A
4 赵六 G
------解决方案-------------------- create table C(Cid int,CName varchar(100))
go
insert into C
select 1, '张三 ' union all
select 2, '李四 ' union all
select 3, '王五 ' union all
select 4, '赵六 '
create table j(JID int,CID int,Jname varchar(100))
insert into j
select 1,1, 'A ' union all
select 2,1, 'B ' union all
select 3,3, 'A ' union all
select 4,2, 'W ' union all
select 5,4, 'G ' union all
select 6,1, 'V ' union all
select 7,1, 'X '
go
--写一个聚合函数:
create function dbo.fn_Merge(@id int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+ ', '+JName from j where CID=@id
return stuff(@r,1,1, ' ')
end
go
-- 调用函数
select Cid, CName,dbo.fn_Merge(cid) as JName from C
go
drop table C,J
drop function fn_Merge