资源描述:
《sql中合并多行记录的方法总汇》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、SQL中合并多行记录的方法总汇-- =============================================================================-- Title: 在SQL中分类合并数据行-- Author: dobear Mail(MSN): dobear_0922@hotmail.com-- Environment: Vista + SQL2005-- Date: 2008-04-22-- ==============================================
2、===============================--1. 创建表,添加测试数据CREATE TABLE tb(id int, [value] varchar(10))INSERT tb SELECT 1, 'aa'UNION ALL SELECT 1, 'bb'UNION ALL SELECT 2, 'aaa'UNION ALL SELECT 2, 'bbb'UNION ALL SELECT 2, 'ccc'--SELECT * FROM tb/**//*id value----------- ---------
3、-1 aa1 bb2 aaa2 bbb2 ccc(5 row(s) affected)*/--2 在SQL2000只能用自定义函数实现----2.1 创建合并函数fn_strSum,根据id合并value值GOCREATE FUNCTION dbo.fn_strSum(@id int)RETURNS varchar(8000)ASBEGIN DECLARE @values varchar(8000) SET @values = ''
4、 SELECT @values = @values + ',' + value FROM tb WHERE id=@id RETURN STUFF(@values, 1, 1, '')ENDGO-- 调用函数SELECT id, VALUE = dbo.fn_strSum(id) FROM tb GROUP BY idDROP FUNCTION dbo.fn_strSum----2.2 创建合并函数fn_strSum2,根据id合并value值GOCREATE FUNCTION dbo.fn_strSum2(@id int)RETUR
5、NS varchar(8000)ASBEGIN DECLARE @values varchar(8000) SELECT @values = isnull(@values + ',', '') + value FROM tb WHERE id=@id RETURN @valuesENDGO-- 调用函数SELECT id, VALUE = dbo.fn_strSum2(id) FROM tb GROUP BY idDROP FUNCTION dbo.fn_strSum2--3 在SQL2005中的新解法----3.1
6、使用OUTER APPLYSELECT * FROM (SELECT DISTINCT id FROM tb) A OUTER APPLY( SELECT [values]= STUFF(REPLACE(REPLACE( ( SELECT value FROM tb N WHERE id = A.id FOR XML AUTO ), '', ''), 1
7、, 1, ''))N----3.2 使用XMLSELECT id, [values]=STUFF((SELECT ','+[value] FROM tb t WHERE id=tb.id FOR XML PATH('')), 1, 1, '')FROM tbGROUP BY id--4 删除测试表tbdrop table tb/**//*id values----------- --------------------1 aa,bb2 aaa,bbb,ccc(2 row(s) affec
8、ted)*/--来自csdn,这篇文章很不错.