SQL Server: Merge multiple rows into one row and perform grouping statistics.

Source: Internet
Author: User

Copy codeThe Code is as follows: -- create a test table and insert data

Create table test (code varchar (50), [values] varchar (10), [count] int)
INSERT test SELECT '001', 'AA', 1
Union all select '001', 'bb ', 2
Union all select '002 ', 'aaa', 4
Union all select '002 ', 'bbb', 5
Union all select '002 ', 'ccc', 3;

-- Method 1
-- Merge multiple rows into one row and perform grouping statistics
SELECT code,
[Values] =
Stuff (B. [values]. value ('/R [1]', 'nvarchar (max )'),
,
,
''), [Count]
FROM (SELECT code, sum ([count]) as [count]
FROM test
Group by code)
CROSS apply (
SELECT [values] = (
SELECT n', '+ [values] FROM test
WHERE code = a. code
For xml path (''), ROOT ('R'), TYPE
)
) B;

-- Method 2

--- The new solution in SQL2005 uses XML

SELECT code, data = STUFF (SELECT ',' + [values] FROM test t WHERE code = t1.code for xml path (''), 1, 1 ,''), sum ([count]) as [count]
FROM test t1
Group by code

-- Query Result

-- 001 aa, bb 3
-- 002 aaa, bbb, ccc 12

Drop table test

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.