文章目录
- 题目
- 一、分析
- 二、题解
- 1.SqlServer
- 2.MySQL
- 3.Oracle
- 总结
题目
查询“OCCUPATIONS”中的“Occupation”列,使每个姓名按字母顺序排序,并显示在其相应的“职业》下方。输出列标题应分别为Doctor、Professor、Singer和Actor。
注意:当不再有与某个职业对应的名称时,打印NULL。
输入格式
职业表描述如下:
职业只包含以下值之一:博士、教授、歌手或演员。
样本输入
样本输出
Jenny Ashley Meera Jane
Samantha Christeen Priya Julia
NULL Ketty NULL Maria
一、分析
以SqlServer为例:
1.输出列标题应分别为Doctor、Professor、Singer和Actor
可以使用Pivot把行转为列:Pivot (max(name) for Occupation in ([Doctor],[Professor],[Singer], [Actor])) as b
2、使每个姓名按字母顺序排序,通过窗口函数进行排序row_number() over(PARTITION by Occupation order by name)
二、题解
1.SqlServer
代码如下(示例):
select Doctor,Professor,Singer, Actor from (select Occupation,Name, row_number() over(PARTITION by Occupation order by name) rom
from OCCUPATIONS ) as a
Pivot (max(name) for Occupation in ([Doctor],[Professor],[Singer], [Actor])) as b
2.MySQL
代码如下(示例):
SELECT MAX(C1), MAX(C2), MAX(C3), MAX(C4) FROM
(SELECT
COUNT(*) Rank,
IF (STRCMP(T1.Occupation, 'Doctor') = 0, T1.Name, NULL) AS C1,
IF (STRCMP(T1.Occupation, 'Professor') = 0, T1.Name, NULL) AS C2,
IF (STRCMP(T1.Occupation, 'Singer') = 0, T1.Name, NULL) AS C3,
IF (STRCMP(T1.Occupation, 'Actor ') = 0, T1.Name, NULL) AS C4
FROM Occupations T1 LEFT JOIN Occupations T2 ON T1.Occupation = T2.Occupation AND STRCMP(T1.Name, T2.Name) >= 0 GROUP BY T1.Name, T1.Occupation ORDER BY Rank, T1.Name) AS MyOccupations GROUP BY Rank;
3.Oracle
代码如下(示例):
WITH D AS (SELECT NAME, ROWNUM R FROM (SELECT NAME FROM OCCUPATIONS WHERE OCCUPATION='Doctor' ORDER BY 1)),
P AS (SELECT NAME, ROWNUM R FROM (SELECT NAME FROM OCCUPATIONS WHERE OCCUPATION='Professor' ORDER BY 1)),
S AS (SELECT NAME, ROWNUM R FROM (SELECT NAME FROM OCCUPATIONS WHERE OCCUPATION='Singer' ORDER BY 1)),
A AS (SELECT NAME, ROWNUM R FROM (SELECT NAME FROM OCCUPATIONS WHERE OCCUPATION='Actor' ORDER BY 1))
SELECT D.NAME,P.NAME,S.NAME,A.NAME
FROM
A FULL OUTER JOIN D ON A.R=D.R
FULL OUTER JOIN S ON A.R=S.R
FULL OUTER JOIN P ON A.R=P.R;
总结
题目有很多种解法,上面只是其中三种解法,各位博主有其他解法欢迎分享!!!