【SQL每日一练】查询“OCCUPATIONS”中的“Occupation”列并按Doctor、Professor、Singer、Actor列输出

文章目录


题目

查询"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

代码如下(示例):

c 复制代码
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

代码如下(示例):

c 复制代码
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;

总结

题目有很多种解法,上面只是其中三种解法,各位博主有其他解法欢迎分享!!!

相关推荐
上山的月21 分钟前
MySQL -函数和约束
数据库·mysql
zhcf24 分钟前
【MySQL】十三,关于MySQL的全文索引
数据库·mysql
极限实验室25 分钟前
Easysearch Chart Admin 密码自定义
数据库
丁总学Java33 分钟前
要查询 `user` 表中 `we_chat_open_id` 列不为空的用户数量
数据库·mysql
抓哇能手33 分钟前
数据库系统概论
数据库·人工智能·sql·mysql·计算机
littlegirll34 分钟前
一个从oracle使用spool导出数据到kadb的脚本
数据库·oracle
geovindu36 分钟前
CSharp: Oracle Stored Procedure query table
数据库·oracle·c#·.net
油丶酸萝卜别吃1 小时前
MyBatis中XML文件的模板
xml·数据库·mybatis
三天不学习1 小时前
【Select 语法全解密】.NET开源ORM框架 SqlSugar 系列
数据库·.net·orm·微软技术·sqlsugar
CC呢1 小时前
基于单片机的智能婴儿床监护系统多功能婴儿床摇篮系统
数据库·mongodb