2013-08-26 49 views
5

我在爲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中編寫此查詢?

回答

4

這裏有一個辦法做到這一點:

;with PersonCityGroupPreferences as (
    select 
    Person, 
    Priority, 
    stuff ((
     select ', ' + d2.City 
     from DummyTable d2 
     where d1.Priority = d2.Priority 
      and d1.Person = d2.Person 
     FOR XML PATH('') 
    ), 1, 2, '') Cities 
    from DummyTable d1 
    group by Person, Priority 
) 
select 
    Cities, 
    stuff ((
    select ', ' + p2.Person 
    from PersonCityGroupPreferences p2 
    where p1.Cities = p2.Cities 
     and p1.Priority = p2.Priority 
    FOR XML PATH('') 
), 1, 2, '') Persons, 
    Priority 
from PersonCityGroupPreferences p1 
group by Priority, Cities 

SQLFiddle鏈接:http://www.sqlfiddle.com/#!3/d831d/57

爲了達到最終的結果,我將解決方案分爲兩步:

  1. 獲取設置結果組由PersonPriority和包含城市作爲第三列

  2. 以獲得1點的結果集,做同樣的事情逗號分隔的列表,但現在組數據在列Cities(逗號分隔的列表)和Priority之間,併產生一個以逗號分隔的對應人員列表。

在上面的查詢,步驟1是此查詢:

select 
    Person, 
    Priority, 
    stuff ((
    select ', ' + d2.City 
    from DummyTable d2 
    where d1.Priority = d2.Priority 
    and d1.Person = d2.Person 
    FOR XML PATH('') 
), 1, 2, '') Cities 
from DummyTable d1 
group by Person, Priority 

這裏的部分結果如何看在SQL:http://www.sqlfiddle.com/#!3/d831d/58

我然後暴露所述第一查詢爲CTE,使得它可用於(外部)查詢2,它基本上做同樣的事情,但具有不同的分組標準。

0

我認爲你可以在最大達到這一點:http://www.sqlfiddle.com/#!3/d831d/26

SELECT 
(SELECT 
    STUFF((SELECT ', ' + d.City 
    FROM (SELECT DISTINCT d2.City FROM dbo.DummyTable d2 
     WHERE d2.Priority = d1.Priority and d2.City = d1.City) 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 and d2.City = d1.City) d 
    FOR XML PATH('')), 1, 2, '') 
) 
AS Person, 
d1.Priority 
FROM 
dbo.DummyTable d1 
GROUP BY d1.Priority,d1.City