分组查询中每组中某列的各行字符数据相加显示,即把每组中多行数据的某列通过字符相加显示成一行。
例如:分组查询的结果如下,
type name score
1 frank 90
1 joane 80
2 tom 100
2 jack 50
3 dong 99
3 bruce 90
我想要的结果是
type names sumScore
1 frankjoane 170
2 tomjack 150
3 dongbruce 189
请高手帮我写写这个sql语句,谢谢!
CREATE FUNCTION dbo.f_str(@type int) RETURNS varchar(8000) AS BEGIN DECLARE @r varchar(8000) SET @r = '' SELECT @r = @r + [name] FROM tb WHERE [type]=@type RETURN STUFF(@r, 1, 1, '') END GO SELECT [TYPE],dbo.f_str([TYPE]),SUM([score]) FROM TB GROUP BY [TYPE]
用函数来做