2013-08-23 116 views
0

使用MS-SQL我正在尋找構建條件交叉表查詢的最佳方法,我猜是描述它的最好方法。SQL Server條件交叉表

在這裏簡化它,我有一個CLIENTS數據集(每個都有一個唯一的ID)。每個客戶端都被分配到一個TEAM。大多數客戶只能分配到1個團隊,但有些可以分配到2個,3個或最多5個團隊。我想我的查詢結果如下所示:

Client_ID Assigned_Team1 Assigned_Team2 Assigned_Team3 Assigned_Team4 Assigned_Team5 
--------- -------------- -------------- -------------- -------------- -------------- 
87496  Red Team  Null   Null   Null   Null 
74559  Red Team  Blue Team  White Team  Null   Null 
56345  Blue Team  Green Team  Null   Null   Null 
21473  Yellow Team  Blue Team  White Team  Red Team  Green Team 

回答

1

爲了得到你將要使用row_number()結果。 row_number將用於爲client_id的每個團隊分配一個連續值。然後使用該序列號將結果轉換爲列。有幾種方法可以將數據行轉換爲列。 (注:我猜對錶結構)

可以使用聚合函數CASE表達式:

select client_id, 
    max(case when seq = 1 then team end) Assigned_Team1, 
    max(case when seq = 2 then team end) Assigned_Team2, 
    max(case when seq = 3 then team end) Assigned_Team3, 
    max(case when seq = 4 then team end) Assigned_Team4, 
    max(case when seq = 5 then team end) Assigned_Team5 
from 
(
    select client_id, team, 
    row_number() over(partition by client_id order by team) seq 
    from clients 
) d 
group by client_id; 

SQL Fiddle with Demo

或者你也可以使用旋轉功能:

select client_id, 
    [1] Assigned_Team1, 
    [2] Assigned_Team2, 
    [3] Assigned_Team3, 
    [4] Assigned_Team4, 
    [5] Assigned_Team5 
from 
(
    select client_id, team, 
    row_number() over(partition by client_id order by team) seq 
    from clients 
) d 
pivot 
(
    max(team) 
    for seq in ([1], [2], [3], [4], [5]) 
) piv; 

SQL Fiddle with Demo