0

How to make row data comma-separated in SQL Server?

CREATE TABLE CountryState
(Country Varchar(15), State Varchar(15))
GO

INSERT INTO CountryState VALUES('India','MH')
INSERT INTO CountryState VALUES('India','DL')
INSERT INTO CountryState VALUES('US','NJ')
INSERT INTO CountryState VALUES('US','NY')
GO

SELECT * FROM CountryState

Output:

Country State
----------------------------    
India   MH
India   DL
US  NJ
US  NY

I require output in following format.

Country State
------------------    
India   MH,DL
US          NJ,NY   
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

1 Answers1

4

There are many ways to do this, but you can use FOR XML PATH to do it in a reasonably concise way.

SELECT DISTINCT Country, 
                STUFF((SELECT ',' + State 
                       FROM CountryState cs 
                       WHERE CountryState.Country = cs.Country
                       FOR XML PATH ('')), 1, 1, '')
FROM CountryState;

An SQLfiddle to test with.

Joachim Isaksson
  • 170,943
  • 22
  • 265
  • 283