简体   繁体   中英

SQL Server Pivoting a Query

I am using SQL Server and am trying to list Names by Occupation, could someone help me understand why below wouldn't work? Here is the original question source: 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;

I would use row_number() to rank names for each occupation, and then conditional aggregation to pivot the dataset:

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

Demo on DB Fiddle

Sample data:

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

Results:

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

You should write your column in select and use aggregate function like count on your query.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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