我需要在此处更改此表
name occupation
samantha doctor
julia actor
maria actor
meera singer
ashley professor
ketty professor
christen professor
jane actor
penny doctor
priya singer
我需要按Doctor,Professor,Singer,Actor-
的列顺序进行输出Jenny Ashley Meera Jane
Samantha Christeen Priya Julia
NULL Ketty NULL Maria
I tried
Select [Doctor],[Professor],[Singer],[Actor]
From (Select Occupation,NAme From Occupations) Pivot (Max(NAme) For Occupation in ([Doctor],[Professor],[Singer],[Actor]))a;
答案 0 :(得分:1)
您可以使用row_number()
函数:
select max(case when occupation = 'doctor' then name end) as doctor,
. . .
from (select *, row_number() over (partition by occupation order by name) seq
from table
) t
group by seq;
答案 1 :(得分:1)
DECLARE @Occupasions TABLE(
name VARCHAR(100),
Occupation VARCHAR(100)
)
INSERT INTO @Occupasions VALUES
('samantha', 'doctor'),
('julia', 'Actor'),
('samantha', 'Singer'),
('tuhin', 'doctor'),
('ketty', 'professor');
SELECT [doctor],[Actor],[Singer],[professor]
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
FROM @Occupasions
) as t
PIVOT (
MAX(Name) FOR Occupation IN ([doctor],[Actor],[Singer],[professor])
) as pvt
答案 2 :(得分:0)
SET @r1=0, @r2=0, @r3 =0, @r4=0;
SELECT MIN(Doctor), MIN(Professor), MIN(Singer), MIN(Actor) FROM
(SELECT CASE Occupation WHEN 'Doctor' THEN @r1:=@r1+1
WHEN 'Professor' THEN @r2:=@r2+1
WHEN 'Singer' THEN @r3:=@r3+1
WHEN 'Actor' THEN @r4:=@r4+1 END
AS RowLine,
CASE WHEN Occupation = 'Doctor' THEN Name END AS Doctor,
CASE WHEN Occupation = 'Professor' THEN Name END AS Professor,
CASE WHEN Occupation = 'Singer' THEN Name END AS Singer,
CASE WHEN Occupation = 'Actor' THEN Name END AS Actor
FROM OCCUPATIONS ORDER BY Name) AS t
GROUP BY RowLine;
链接:https://nifannn.github.io/2018/06/01/SQL-%E7%AC%94%E8%AE%B0-Hackerrank-Occupations/