我在爲sqlserver2008創建SQL語句時遇到問題。我有以下數據:兩個組列的SQL語句
city person priority
-----------------------------------
Linz Mike 1
Wien Mike 1
Linz Tom 1
Wien Tom 1
Linz John 1
Linz Sarah 2
這意味着人邁克和湯姆選擇城市林茨和維也納優先1.
約翰選擇林茨優先1.
莎拉選擇林茨優先2.
現在我想下面的輸出:
cities persons priority
-----------------------------------
Linz, Wien Mike, Tom 1
Linz John 1
Linz Sarah 2
我已經有下面的SQL語句,但我沒有得到預期的結果,因爲這查詢會說約翰也有條目維也納優先1.
SELECT
(SELECT
STUFF((SELECT ', ' + d.City
FROM (SELECT DISTINCT d2.City FROM dbo.DummyTable d2
WHERE d2.Priority = d1.Priority) d
FOR XML PATH('')), 1, 2, '')
)
AS Cities,
(SELECT
STUFF((SELECT ', ' + d.Person
FROM (SELECT DISTINCT d2.Person FROM dbo.DummyTable d2
WHERE d2.Priority = d1.Priority) d
FOR XML PATH('')), 1, 2, '')
)
AS Persons,
d1.Priority
FROM
dbo.DummyTable d1
GROUP BY d1.Priority
您也可以使用此SQL Fiddle
任何想法如何可以在SQL中編寫此查詢?