SQL合并行
表名:UserDuty
id Name Dsp level
1 | Designer | 1 | 1 |
2 | Coder | 1 | 2 |
3 | Coder | 2 | 3 |
4 | Coder | 3 | 4 |
5 | Designer | 2 | 0 |
NULL | NULL | NULL | NULL |
// 合并数值
Create FUNCTION dbo.f_sum(@name varchar(100))
RETURNS int
AS
BEGIN
DECLARE @r int
SET @r = 0
SELECT @r = @r + [level]
FROM UserDuty
WHERE [Name]=@name
RETURN @r
END
GO
// 合并行字符串
Create FUNCTION dbo.f_str(@name varchar(100))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r = ''
SELECT @r = @r+',' + rtrim([Dsp])
FROM UserDuty
WHERE [Name]=@name
RETURN STUFF(@r, 1, 1, '')
END
GO
// 调用函数
SELECT [Name], [Dsp]=dbo.f_str([Name]) ,[level]=dbo.f_sum([Name])
FROM UserDuty
GROUP BY [Name]