0

Using MS-SQL I am looking for the best way to construct a conditional crosstab query I guess is the best way to describe it.

Simplifying it here, I have a dataset of CLIENTS (each with a unique ID). Each of these clients is assigned to a TEAM. Most clients are assigned to only 1 team, however some can be assigned to 2, 3 or up to 5 teams. I would like my query results to look like the following:

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
4

1 回答 1

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

或者您可以使用 PIVOT 功能:

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

于 2013-08-23T00:30:07.277 回答