[英]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?我正在使用 SQL 服务器并尝试按职业列出名称,有人可以帮我理解为什么下面不起作用吗? 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
这是原始问题来源: 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:我将使用
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
Demo on DB Fiddle 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 中写入您的列,并在查询中使用聚合 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.