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)