Sql 以逗号分隔格式显示按项目分组

Sql 以逗号分隔格式显示按项目分组,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张如下表: create table Location ( ContinentID int not null, CountryID int not null, StateCode nvarchar(10) not null ) Insert into Location Values (1, 1, 'AP') Insert into Location Values (1, 1, 'WB') Insert into Location Values (1, 1, 'MH') Insert in

我有一张如下表:

create table Location
(
ContinentID int not null,
CountryID int not null,
StateCode nvarchar(10) not null
)

Insert into Location Values (1, 1, 'AP')
Insert into Location Values (1, 1, 'WB')
Insert into Location Values (1, 1, 'MH')
Insert into Location Values (1, 2, 'KA')
Insert into Location Values (1, 2, 'ID')
Insert into Location Values (3, 1, 'NY')
Insert into Location Values (3, 1, 'WA')
Insert into Location Values (3, 2, 'VI')
ContinentID     CountryID    StateCodes
-----------     ---------    ----------
1               1            AP,WB,MH
1               2            KA,ID
3               1            NY,WA
3               2            VI
在这里,我需要所有的州代码都以逗号分隔的格式显示,格式基于大陆ID和国家ID。因此,输出必须如下所示:

create table Location
(
ContinentID int not null,
CountryID int not null,
StateCode nvarchar(10) not null
)

Insert into Location Values (1, 1, 'AP')
Insert into Location Values (1, 1, 'WB')
Insert into Location Values (1, 1, 'MH')
Insert into Location Values (1, 2, 'KA')
Insert into Location Values (1, 2, 'ID')
Insert into Location Values (3, 1, 'NY')
Insert into Location Values (3, 1, 'WA')
Insert into Location Values (3, 2, 'VI')
ContinentID     CountryID    StateCodes
-----------     ---------    ----------
1               1            AP,WB,MH
1               2            KA,ID
3               1            NY,WA
3               2            VI
我对SQL查询不太了解,我尝试了下面的一个查询,但没有成功:

SELECT Continentid, CountryID, CONCAT(StateCode, ',') FROM Location
GROUP BY Continentid, CountryID

如何使用单个SQL查询获得所需的输出?非常感谢您的帮助。

啊-这很棘手:这里有一种适合您的数据结构的方法。我已经验证过它会产生你想要的结果,除了一个尾随的逗号

在T-SQL中,可能会提供最好的性能。处理不适当的前导逗号

选择大陆ID、国家ID、, 州代码= 填充选择“,”+状态代码 从位置b 其中b.ContinentID=a.ContinentID 和 b、 CountryID=a.CountryID 对于XML路径,1,2, 从地点a 按大陆ID、国家ID分组