【SQL每日一练】获取PADS公司用户名称和各职业总数并根据格式输出

发布于:2024-05-15 ⋅ 阅读:(153) ⋅ 点赞:(0)


题目

生成以下两个结果集:

1、查询 OCCUPATIONS 表中所有名字,紧跟每个职业的第一个字母作为括号(即:括在括号中),并按名字顺序排序。例如:AnActorName(A) ADoctorName(D) AProfessorName(P) ASingerName(S)
2、查询 OCCUPATIONS 中每个职业的出现次数。按升序对出现次数进行排序,并按以下格式输出:

There are a total of [occupation_count] [occupation]s.

其中occupation_count 是 OCCUPATIONS 中职业的出现次数,occupation是小写的职业名称。如果多个职业具有相同的内容,则应按字母顺序排列。

注意:每种类型的职业在表中至少有两个条目。

OCCUPATIONS 表描述如下:

在这里插入图片描述
Occupation 将仅包含以下值之一:Doctor、Professor、Singer 或 Actor。

示例输入
包含以下记录的 OCCUPATIONS 表:

在这里插入图片描述

示例输出

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are a total of 2 doctors.
There are a total of 2 singers.
There are a total of 3 actors.
There are a total of 3 professors.

一、解析

1、获取名称+职业首字母 AnActorName(A)
MySQL使用concat(Name,'(',substring(Occupation,1,1),')')
2、获取每个职业的出现次数,输出格式There are a total of [occupation_count] [occupation]s.
每个职业的出现次数:count(*)
小写的职业名称:lower(Occupation)

使用concat进行拼接

concat('There are a total of ', count(1),' ',lower(Occupation),'s.')

二、题解

1.MySQL

代码如下(示例):


select concat(Name,'(',substring(Occupation,1,1),')')   from OCCUPATIONS order by name;
select concat('There are a total of ', count(1),' ',lower(Occupation),'s.') from OCCUPATIONS group by Occupation order by count(Occupation),Occupation

网站公告

今日签到

点亮在社区的每一天
去签到