String Merge after group by in SQL Server

Source: Internet
Author: User

Reference:

1. After the SQL query statement group BY, the string merge

2. SQL FOR XML Path usage

#需求:
 Merge the column value table structure with the following data: ID value-----  ------ 1AA1BB2AAA2BBB2CCC needs to get results: IDValues -----  ------------ 1AA,BB2AAA,BBB,CCC is:  Group  by ID, sum of Value (string addition) 
#解决方法: 1, traditional method: Create a handler function (SQL Server 2000 can only use this method)
Create TableTB (IDint, valuevarchar(Ten)) Insert  intoTbValues(1,'AA') Insert  intoTbValues(1,'BB') Insert  intoTbValues(2,'AAA') Insert  intoTbValues(2,'BBB') Insert  intoTbValues(2,'CCC') Go --1. Create a handler functionCREATE FUNCTIONDbo.f_strunite (@id int) RETURNS varchar(8000)  as BEGIN     DECLARE @str varchar(8000)     SET @str = "'     SELECT @str = @str + ',' +Value fromTbWHEREId=@id     RETURN STUFF(@str,1,1,"') END GO --calling FunctionsSELECtID, value=Dbo.f_strunite (ID) fromTbGROUP  byIDDrop TableTBDrop functionDbo.f_struniteGo/*ID value---------------------1 aa,bb 2 AAA,BBB,CCC (the number of rows affected is 2 rows)*/ 
2. New workaround: Take advantage of the FOR XML path (SQL Server 2005 and later versions)
SelectId[Values]=Stuff(    (        Select ','+[value]  fromTB TwhereId=Tb.id forXML Path ("')    ),    1,     1,     "')  fromTBGroup  byID/*ID values-----------------------------1 aa,bb 2 AAA,BBB,CCC (2 row (s) affected)*/ 

String Merge after group by in SQL Server

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.