SQL Server: Two ways to combine multiple lines into one row and do grouping statistics _mssql

Source: Internet
Author: User
Copy Code code as follows:

--Create test table, insert data

CREATE TABLE Test (code varchar (), [values] varchar (a), [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 One
--Combine multiple lines into one row and do grouped 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) a
CROSS Apply (
SELECT [Values] = (
SELECT N ', ' + [values] from test
WHERE Code = A.code
For XML PATH ('), ROOT (' R '), TYPE
)
) b;



--Method Two

A new solution to the---SQL2005 using 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 results

--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.