例如:有一个表m
jid no fid
1 1003 5
2 1003 6
3 1005 65
4 1006 81
5 1006 89想通过类似这样一个语句实现
select ?(fid) from m group by no no fid
1003 5,6
1005 65
1006 81,89
请问该如何处理?
jid no fid
1 1003 5
2 1003 6
3 1005 65
4 1006 81
5 1006 89想通过类似这样一个语句实现
select ?(fid) from m group by no no fid
1003 5,6
1005 65
1006 81,89
请问该如何处理?
no,
stuff((select ','+ltrim(fid) from m where no=t.no for xml path('')),1,1,'')
from
m t
group by no
以上适用于sql2005及以上的版本,sql2000用函数
go
create table [m]([jid] int,[no] int,[fid] int)
insert [m]
select 1,1003,5 union all
select 2,1003,6 union all
select 3,1005,65 union all
select 4,1006,81 union all
select 5,1006,89
gocreate function f_str(@no varchar(20))
returns varchar(50)
as
begin
declare @s varchar(800)
select @s=isnull(@s+',','')+ltrim(fid)
from m
where no=@no
return @s
end
goselect no,dbo.f_str(no) as fid from m group by no--测试结果:
/*
no fid
----------- --------------------------------------------------
1003 5,6
1005 65
1006 81,89(所影响的行数为 3 行)
*/
jid no fid gid
1 1003 5 10
2 1003 6 20
3 1005 65 30
4 1006 81 40
5 1006 89 20想得到的结果是
no fid gid
1003 5,6 10,20
1005 65 30
1006 81,89 40,20
这个函数该如何写呢
写两个函数,方法同上(另起一个函数名称,把字段fid改为gid即可)