簡體   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