SQL combines repeating rows of data into one row with data separated by commas

Source: Internet
Author: User

1 I. Defining table Variables2 3 DECLARE @T1 Table4 (5Useridint , 6UserNamenvarchar( -),7CityNamenvarchar( -)8 );9 Ten Insert  into @T1(Userid,username,cityname)Values(1,'a','Shanghai') One Insert  into @T1(Userid,username,cityname)Values(2,'b','Beijing') A 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') the  - Select *  from @T1 -  - -----The best way + SELECTCityName,STUFF((SELECT ',' +UserName from @T1SubTitleWHERECityName=A.cityname forXML PATH ("')),1,1,"') asA -  from @T1A + GROUP  byCityName A  at ----The second way - SELECTB.cityname, Left(UserList,LEN(userlist)-1)  -  from ( -   SELECTCityName, (SELECTUserName+','  from @T1 WHERECityName=A.cityname forXML PATH ("')) asuserlist -    from @T1A -   GROUP  byCityName in ) B -  to Stuff(Select ',' +FieldName fromTableName forXML Path ("')),1,1,"') + The function of this whole sentence is to concatenate the contents of a multiline FieldName field, separated by commas.  -  the  forXML Path is a way to generate XML that is supported by versions of SQL Server 2005.  *  $The role of the stuff function is to remove the comma delimiter from the front of the string.

SQL combines repeating rows of data into one row with data separated by commas

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.