Avatar of crompnk
crompnkFlag for United Kingdom of Great Britain and Northern Ireland asked on

Comma delimited list, tsql

Hi,
I would like to amalgamate values from multiple rows into a comma delimited list but group by another column (key), so for example the outcome would be:

Name     Group
Address  Home,Work
City         Home,Work

CREATE TABLE TEMPTABLE(

             [NAME] [varchar] (20),
             [GROUP] [varchar] (20)
             )
GO
INSERT INTO TEMPTABLE([NAME], [GROUP]) VALUES ('Address','Home')
INSERT INTO TEMPTABLE([NAME], [GROUP]) VALUES ('City','Home')
INSERT INTO TEMPTABLE([NAME], [GROUP]) VALUES ('Address','Work')
INSERT INTO TEMPTABLE([NAME], [GROUP]) VALUES ('City','Work')
GO

SELECT [NAME]
FROM TEMPTABLE

DROP TABLE TEMPTABLE

Open in new window


SELECT List = STUFF((
			SELECT DISTINCT ', ' + QUOTENAME([GROUP], '''')
			FROM (SELECT * FROM TEMPTABLE) x
			FOR XML PATH('')
				,TYPE
			).value('.', 'VARCHAR(8000)'), 1, 3, '')

Open in new window

Microsoft SQL Server 2005SQL

Avatar of undefined
Last Comment
PortletPaul

8/22/2022 - Mon
Éric Moreau

SELECT DISTINCT Name
, STUFF(
       (SELECT ', ' + QUOTENAME([GROUP], '''')
        FROM TempTable
        WHERE Name = R.Name
        ORDER BY [Group]
        FOR XML PATH('')
       )
       , 1
       , 2
       , '') AS List FROM TempTable AS R
ASKER CERTIFIED SOLUTION
PortletPaul

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23