繁体   English   中英

SQL 服务器透视查询

[英]SQL Server Pivoting a Query

我正在使用 SQL 服务器并尝试按职业列出名称,有人可以帮我理解为什么下面不起作用吗? 这是原始问题来源: https://www.hackerrank.com/challenges/occupations/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen

select *
from (select Name, Occupation from OCCUPATIONS)
PIVOT(Name for Occupation in ([Doctor],[Professor],[Singer],[Actor])) as pivot_table;

我将使用row_number()对每个职业的名称进行排名,然后将条件聚合到 pivot 数据集:

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
) t
group by rn

DB Fiddle 上的演示

样本数据:

name      | occupation
:-------- | :---------
Samantha  | Doctor    
Julia     | Actor     
Maria     | Actor     
Meera     | Singer    
Ashely    | Professor 
Ketty     | Professor 
Christeen | Professor 
Jane      | Actor     
Jenny     | Doctor    
Priya     | Singer    

结果:

doctor   | professor | singer | actor
:------- | :-------- | :----- | :----
Jenny    | Ashely    | Meera  | Jane 
Samantha | Christeen | Priya  | Julia
null     | Ketty     | null   | Maria

您应该在 select 中写入您的列,并在查询中使用聚合 function 之类的count

select 'count' as name_count, 
    [Doctor],
    [Professor],
    [Singer],
    [Actor] 
from (select Name, Occupation from OCCUPATIONS) as s_t
PIVOT(Count(Name) for Occupation in ([Doctor],[Professor],[Singer],[Actor])) as pivot_table;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM