SQL statement to merge multiple rows of records

Source: Internet
Author: User

Method for merging multiple rows of records in SQL:
-- 1. Create a table and add Test Data
Create table tb (id int, [value] varchar (10 ))
INSERT tb SELECT 1, 'A'
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
---------------------
1 aa
1 bb
2 aaa
2 bbb
2 ccc
(5 row (s) affected)
*/
-- 2 in SQL2000, only user-defined functions can be used.
---- 2.1 create the merging function fn_strSum and merge value values based on id
GO
Create function dbo. fn_strSum (@ id int)
RETURNS varchar (8000)
AS
BEGIN
DECLARE @ values varchar (8000)
SET @ values =''
SELECT @ values = @ values + ',' + value FROM tb WHERE id = @ id
Return stuff (@ values, 1, 1 ,'')
END
GO
-- Call a function
SELECT id, VALUE = dbo. fn_strSum (id) FROM tb group by id
Drop function dbo. fn_strSum
---- 2.2 create the merging function fn_strSum2 and merge value values based on id
GO
Create function dbo. fn_strSum2 (@ id int)
RETURNS varchar (8000)
AS
BEGIN
DECLARE @ values varchar (8000)
SELECT @ values = isnull (@ values + ',', '') + value FROM tb WHERE id = @ id
RETURN @ values
END
GO
-- Call a function
SELECT id, VALUE = dbo. fn_strSum2 (id) FROM tb group by id
Drop function dbo. fn_strSum2
-- 3 new solution in SQL2005/SQL2008
---- 3.1 Use OUTER APPLY
SELECT *
FROM (select distinct id FROM tb) a outer apply (
SELECT [values] = STUFF (REPLACE (
(
SELECT value FROM tb N
WHERE id = A. id
FOR XML AUTO
), '<N value = "', ','), '"/>', ''), 1, 1 ,'')
) N
---- 3.2 use XML
SELECT id, [values] = STUFF (SELECT ',' + [value] FROM tb t WHERE id = tb. id for xml path (''), 1, 1 ,'')
FROM tb
Group by id
-- 4 Delete the test table tb
Drop table tb
/**//*
Id values
-------------------------------
1 aa, bb
2 aaa, bbb, ccc
(2 row (s) affected)
*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.