如何在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
答案 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;