表类似如下: Type Name Amount
K1 A 100
K2 B 100
K2 C 80
K1 D 60
K3 E 120
K3 F 150
K2 G 100
最后结果是: Type Name Amount
K1 A,D 160
K2 B,C,G 280
K3 E,F 270
函数
CREATE FUNCTION MergeCharField(@Group varchar(255))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r=''
SELECT @r=@r+','+rtrim(Name) FROM A WHERE Type=@Group
RETURN(substring(@r,2,8000))
END
GO
--调用
select Type,dbo.MergeCharField(Type),SUM(amount) FROM A GROUP BY type