SQL Server stitching the multiline content of another column of the same ID into one line

Source: Internet
Author: User

For example, there are two columns of data in the table:

ID Name

1 A

1 b

1 c

2 D

2 E


into the following format:

ID Name

1 a,b,c

2 D,e

Data:

if object_id(#表) is  not NULL Drop Table#表SelectDid,name, from#表Order  by didDrop Table#表Select  theNid'AAA'Name1Did into#表Union  AllSelect  the,'BBB',1 Union  AllSelect  the,'CCC',1 Union  AllSelect  the,'DDD',2 Union  AllSelect  -,'Eee',2

The implementation code is as follows:

--recursively computes multiple rows into a single field--Method 1; withx (did, CNT, list, nid, Le) as (SelectDidCount(1) Over(Partition byDID),cast(Name as varchar( -), nid,1  from#表Union  AllSelectX.DID,X.CNT,cast(x.list+','+A.name as varchar( -)), A.nid,x.le+1  from#表 a,xwhereA.did=X.did andA.nid>X.nid)Select *  fromxwhereLe=CNT--Method 2 The intermediate table is not efficientif object_id(#表) is  not NULL Drop Table#结果SelectDidcast(Name as varchar( -)) name into#结果 from#表Order  by didDeclare @dept int ="',@name varchar(Max)="'UpdateaSet @name=  Case  when @dept=Did Then @name+','+nameElsenameEnd,    @dept=Did , name=@name from#结果 aSelectDidMax(name) from#结果Group  by did--Method 3 Using XML is convenient and simple--select ', ' + name from #表 for XML Path (')Selectdid, name=(Stuff((Select ',' +Name from#表whereDid=A.did forXML Path ("')),1,1,"')) from#表 AGroup  byDid

Results:

SQL Server stitching the multiline content of another column of the same ID into one line

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.