数据
列
A B
值
1 a
1 b
1 c
2 d
2 e
3 f我要查询结果为
1 a,b,c
2 d,e
3 f
这个查询语句该如何写?---------------------------------------
--测试--测试数据
create table 表(a int,b varchar(10))
insert 表 select 1,'a'
union all select 1,'a '
union all select 1,'b'
union all select 1,'c'
union all select 2,'d'
union all select 2,'e'
union all select 3,'f'
go--创建处理函数
create function f_merg(@id int)
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+b from 表 where a=@id group by b
return(substring(@re,2,8000))
end
go--调用实现查询
select a,b=dbo.f_merg(a) from 表 group by a
go--删除测试
drop table 表
drop function f_merg/*--测试结果
a b
----------- -----------
1 a,b,c
2 d,e
3 f(所影响的行数为 3 行)
--*/
列
A B
值
1 a
1 b
1 c
2 d
2 e
3 f我要查询结果为
1 a,b,c
2 d,e
3 f
这个查询语句该如何写?---------------------------------------
--测试--测试数据
create table 表(a int,b varchar(10))
insert 表 select 1,'a'
union all select 1,'a '
union all select 1,'b'
union all select 1,'c'
union all select 2,'d'
union all select 2,'e'
union all select 3,'f'
go--创建处理函数
create function f_merg(@id int)
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+b from 表 where a=@id group by b
return(substring(@re,2,8000))
end
go--调用实现查询
select a,b=dbo.f_merg(a) from 表 group by a
go--删除测试
drop table 表
drop function f_merg/*--测试结果
a b
----------- -----------
1 a,b,c
2 d,e
3 f(所影响的行数为 3 行)
--*/
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货