Combine duplicate row data into one row in SQL using commas to separate

Source: Internet
Author: User
Tags sql using

1. Define table Variables
Copy codeThe Code is as follows:
DECLARE @ T1 table
(
UserID int,
UserName nvarchar (50 ),
CityName nvarchar (50)
);

Copy codeThe Code is as follows:
Insert into @ T1 (UserID, UserName, CityName) values (1, 'A', 'shanghai ')
Insert into @ T1 (UserID, UserName, CityName) values (2, 'B', 'beijing ')
Insert into @ T1 (UserID, UserName, CityName) values (3, 'C', 'shanghai ')
Insert into @ T1 (UserID, UserName, CityName) values (4, 'D', 'beijing ')
Insert into @ T1 (UserID, UserName, CityName) values (5, 'E', 'shanghai ')

Copy codeThe Code is as follows:
Select * from @ T1
----- Optimal Method
SELECT CityName, STUFF (SELECT ',' + UserName FROM @ T1 subTitle WHERE CityName = A. CityName for xml path (''), 1, 1,'') AS
FROM @ T1
Group by CityName
---- Method 2
Select B. CityName, LEFT (UserList, LEN (UserList)-1)
FROM (
SELECT CityName, (SELECT UserName + ', 'From @ T1 WHERE CityName = A. CityName for xml path ('') AS UserList
FROM @ T1
Group by CityName
) B
Stuff (select ',' + fieldname from tablename for xml path (''), 1, 1 ,'')

This entire sentence is used to concatenate the content of multiple fieldname fields and separate them with commas.
For xml path is a method supported by SQL Server 2005 and later versions to generate XML.
The purpose of the stuff function is to remove the comma separator at the top of the string.
:

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.