使用MS-SQL我正在寻找构建条件交叉表查询的最佳方法,我猜这是描述它的最佳方式。
在这里简化它,我有一个CLIENTS数据集(每个都有一个唯一的ID)。每个客户端都分配给一个TEAM。大多数客户只被分配到一个团队,但有些可以分配给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
答案 0 :(得分: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;
或者您可以使用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;