按字母顺序排列的数据透视表

问题描述

MysqL的新手,我想透视表
该表仅包含两列NameOccupation,其中null的值都不是inserted

我想枢转职业列,以便每个名称按字母顺序排序并显示在其对应的职业下方。输出标题应为Doctor,Professor,Singer和Actor
我试过这个查询,在哪里可以将它们移到列被旋转的地步

SELECT ( CASE 
           WHEN occupation = 'Doctor' THEN NAME 
           ELSE NULL 
         END ) AS 'Doctor',( CASE 
           WHEN occupation = 'Professor' THEN NAME 
           ELSE NULL 
         END ) AS 'Professor',( CASE 
           WHEN occupation = 'Singer' THEN NAME 
           ELSE NULL 
         END ) AS 'Singer',( CASE 
           WHEN occupation = 'Actor' THEN NAME 
           ELSE NULL 
         END ) AS 'Actor' 
FROM   occupations 
ORDER  BY NAME;

我的输出为:

Aamina NULL NULL NULL
NULL Ashley NULL NULL
NULL Belvet NULL NULL
NULL Britney NULL NULL
NULL NULL Christeen NULL
NULL NULL NULL Eve
NULL NULL Jane NULL
NULL NULL NULL Jennifer
NULL NULL Jenny NULL
Julia NULL NULL NULL
NULL NULL NULL Ketty
NULL NULL Kristeen NULL
NULL Maria NULL NULL
NULL Meera NULL NULL
NULL Naomi NULL NULL
Priya NULL NULL NULL
NULL Priyanka NULL NULL
NULL NULL NULL Samantha

我想不出办法如何获得输出

Aamina Ashley Christeen Eve
Julia Belvet Jane Jennifer
Priya Britney Jenny Ketty
NULL Maria Kristeen Samantha
NULL Meera NULL NULL
NULL Naomi NULL NULL
NULL Priyanka NULL NULL

如果有人可以向我解释,那将非常有帮助。谢谢

解决方法

您可以使用窗口函数(在MySQL 8.0中可用)和聚合来做到这一点:

select 
    max(case when occupation = 'Doctor'    then name end) doctor,max(case when occupation = 'Professor' then name end) professor,max(case when occupation = 'Singer'    then name end) singer,max(case when occupation = 'Actor'     then name end) actor
from (
    select o.*,row_number() over(partition by occupation order by name) rn
    from occupations o
) o
group by rn