sql server 行合并
时间:2011-05-17 来源:lmllouk
SQL SERVER:在SQL中分类合并数据行
--1. 创建表,添加测试数据
CREATE TABLE test(code varchar(50), [values] varchar(10))
INSERT test SELECT '001', 'aa'
UNION ALL SELECT '001', 'bb'
UNION ALL SELECT '002', 'aaa'
UNION ALL SELECT '002', 'bbb'
UNION ALL SELECT '002', 'ccc'
--SELECT * FROM test
code values
----------- ----------
001 aa
001 bb
002 aaa
002 bbb
002 ccc
(5 row(s) affected)
--2 在SQL2000只能用自定义函数实现
----2.1 创建合并函数fn_strSum,根据code合并values值
GO
CREATE FUNCTION dbo.fn_Sum(@code varchar(50))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @values varchar(8000)
SET @values = ''
SELECT @values = @values + ',' + values FROM test WHERE code=@code
RETURN STUFF(@values, 1, 1, '')
END
GO
-- 调用函数
SELECT code, data = dbo.fn_Sum(code) FROM test GROUP BY code
DROP FUNCTION dbo.fn_Sum
----2.2 创建合并函数fnSum,根据code合并values值
GO
CREATE FUNCTION dbo.fnSum(@code varchar(50))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @values varchar(8000)
SELECT @values = Isnull(@values + ',', '') + values FROM test WHERE code=@code
RETURN @values
END
GO
-- 调用函数
SELECT id, VALUE = dbo.fnSum(code) FROM test GROUP BY code
DROP FUNCTION dbo.fnSum
--3 在SQL2005中的新解法
----3.1 使用XML
SELECT code, data=STUFF((SELECT ','+[values] FROM test t WHERE code=t1.code FOR XML PATH('')), 1, 1, '')
FROM test t1
GROUP BY code
--4 删除测试表test
drop table test
/**//*
code data
----------- --------------------
001 aa,bb
002 aaa,bbb,ccc
(2 row(s) affected)