我有一张如下表:
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。所以输出必须如下所示:
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查询获取所需的输出?任何帮助表示赞赏。
答案 0 :(得分:1)
啊 - 这很棘手:)以下是适用于您的数据结构的方法之一。我已经验证它会产生你想要的结果,除了一个尾随的逗号......
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
SELECT p1.ContinentID, p1.CountryID,
( SELECT StateCode + ','
FROM Location p2
WHERE p2.ContinentID = p1.ContinentID AND p2.CountryID = p1.CountryID
ORDER BY StateCode
FOR XML PATH('') ) AS StateCodes
FROM Location p1
GROUP BY ContinentID, CountryID
答案 1 :(得分:1)
在T-SQL中,FOR XML PATH可能会为您提供最佳性能。 STUFF处理以逗号为主的逗号。
Click here to see the SQL Fiddle
SELECT ContinentID, CountryID,
StateCode =
STUFF((SELECT ', ' + StateCode
FROM Location b
WHERE b.ContinentID = a.ContinentID
and
b.CountryID = a.CountryID
FOR XML PATH('')), 1, 2, '')
FROM Location a
GROUP BY ContinentID, CountryID