现在有一个表TableA,如下:
A B
--------------------
1 A
1 B
2 C
2 D
现在想得到下面的结果:
A B
---------------------
1 A,B
2 C,D
要达到这样的结果,怎么用SQL实现?
------解决方案--------------------
create function f_str(@A varchar(10))
returns varchar(100)
as
begin
declare @str varchar(100)
set @str= ' '
select @[email protected]+ ', '+B from tableA where [email protected]
return stuff(@str,1,1, ' ')
end
以上为创建函数
select A,dbo.f_str(A) as B
from tableA
group by A
------解决方案--------------------
create table T(A int, B varchar(10))
insert T select 1, 'A '
union all select 1, 'B '
union all select 2, 'C '
union all select 2, 'D '
create function dbo.fun(@A int)
returns varchar(100)
as
begin
declare @re varchar(100)
set @re= ' '
select @[email protected]+ ', '+B
from T
where [email protected]
return(stuff(@re, 1, 1, ' '))
end
select A, B=dbo.fun(A)
from T
group by A
--result
A B
----------- ----------------------------------------------------------------
1 A,B
2 C,D