这是查询的结果。有许多组合,但最多三个与一个人相关联。
NAME ID GROUPA
=====================
James 20 A
James 20 B
James 20 D
Michael 30 A
Michael 30 B
Michael 30 C
Jordan 40 I
我想要的是......
NAME ID GROUP1 GROUP2 GROUP3
===========================================
James 20 A B D
Michael 30 A B C
Jordan 40 I
我尝试了这个查询,但它不起作用......
SELECT NAME, ID, GROUPA
FROM
(SELECT NAME, ID,
ROW_NUMBER() OVER (PARTITION BY GROUPA ORDER BY EMPLOYEE_ID) AS GROUP
FROM TABLE1)
GROUP BY NAME, ID, GROUPA
感谢您的指导。
答案 0 :(得分:4)
select name,id,
max(case when groupa = 'A' then groupa end) as group1,
max(case when groupa = 'B' then groupa end) as group2,
max( case when groupa = 'C' then groupa end) as group3
from tablename
group by name, id
如果groupa的数量是固定的,则上述查询将起作用。
编辑:使用数据透视
select * from
(select name, id , groupa from tablename)
pivot xml (
max(groupa) for groupa in
(select distinct groupa from tablename)
)
感谢您的解决方案。我快到了。这是我在运行此查询后得到的。实际上有53种不同的GROUPS,因此它增加了53列,但分配给用户的最大组数为5。
NAME ID A B C D E F G H
James 20 A null null null null null null H
Michael 30 A B null null E null null null
我如何得到这样的结果......
NAME ID GROUP_1 GROUP_2 GROUP_3
James 20 A H
Michael 30 A B E
如我在问题中所提到的,如何得到我的结果? 谢谢,
答案 1 :(得分:2)
您可以使用条件聚合和row_number()
:
select name, id,
max(case when seqnum = 1 then groupa end) as group1,
max(case when seqnum = 2 then groupa end) as group2,
max(case when seqnum = 3 then groupa end) as group3
from (select t.*,
row_number() over (partition by name order by employee_id) as seqnum
from table1 t
) t
group by name, id;