如何在SQL Server中分隔行数据逗号

时间:2013-06-29 14:47:28

标签: sql-server sql-server-2008 tsql

如何在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

输出:

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

我需要以下格式输出。

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

1 个答案:

答案 0 :(得分:3)

有很多方法可以执行此操作,但您可以使用FOR XML PATH以合理简洁的方式执行此操作。

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