日期:2014-05-18  浏览次数:20544 次

分组统计问题,谢谢
HY     HU
1       A
2       B
1       C
3       D

需要结果:
HY     HU
1       A,C
2       B
3       D

------解决方案--------------------


create table tb(HY int,HU varchar(100))
go
insert into tb
select 1, 'A ' union all
select 2, 'B ' union all
select 1, 'C ' union all
select 3, 'D '
go
--写一个聚合函数:
create function dbo.fn_Merge(@HY int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r= ' '
select @r=@r+ ', '+HU from tb where HY=@HY
return stuff(@r,1,1, ' ')
end
go

-- 调用函数
select HY, dbo.fn_Merge(HY) as HU from tb group by HY

go
drop table tb
drop function fn_Merge