我从Hackerrank.com遇到了这个sql挑战 样本输入:
select * from occupation
示例输出:
Name Occupation
samantha doctor
jenny doctor
julia actor
maria actor
jane actor
meera singer
priya singer
ashley professor
ketty professor
christeen professor
输出应该是:(医生,教授,歌手,演员也按名称命名)
jenny ashley meera jane
samantha christeen priya julia
null ketty null maria
我试过的是:
SELECT DECODE(occupation,'doctor',name,NULL ),DECODE(occupation,'professor',name,NULL),DECODE(occupation,'singer',name,NULL) ,
DECODE(occupation , 'actor',name,NULL)
FROM occupation ;
但它并没有给我想要的结果。我也试过这个:
SELECT oc1.name ,
oc2.name,oc3.name,oc4.name
FROM
(SELECT name,occupation FROM occupation WHERE occupation = 'doctor'
) oc1 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'actor'
) oc2 ,
(SELECT name,occupation FROM occupation WHERE occupation = 'singer') oc3,
(SELECT name,occupation FROM occupation WHERE occupation = 'professor')oc4 , occupation oc
WHERE
oc1.occupation= oc.occupation(+)
and oc2.occupation = oc.occupation(+)
AND oc3.occupation = oc.occupation(+)
AND oc4.occupation = oc.occupation(+);
但它会提供重复记录。有人可以帮助我吗
由于
答案 0 :(得分:2)
使用PIVOT
:
SELECT doctor, professor, singer, actor
FROM (
SELECT o.*,
ROW_NUMBER() OVER ( PARTITION BY occupation ORDER BY name ) AS rn
FROM occupation o
)
PIVOT ( MAX( name ) FOR Occupation IN (
'doctor' AS doctor,
'actor' AS actor,
'singer' AS singer,
'professor' AS professor
) )
ORDER BY rn;