618.(Hard)学生地理信息报告
一所美国大学有来自亚洲、欧洲和美洲的学生,他们的地理信息存放在如下 student
表中。
name
continent
Jack
America
Pascal
Europe
Xi
Asia
Jane
America
写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。
对于样例输入,它的对应输出是:
America
Asia
Europe
Jack
Xi
Pascal
Jane
进阶:如果不能确定哪个大洲的学生数最多,你可以写出一个查询去生成上述学生报告吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/students-report-by-geography
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
select
max(if(continent='America',name,null)) America
,max(if(continent='Asia',name,null)) Asia
,max(if(continent='Europe',name,null)) Europe
from (
SELECT *
, ROW_NUMBER() over(partition by continent order by name) rownum
from Student
) a
GROUP BY rownum;
Table Schema
Create table If Not Exists student (name varchar(50), continent varchar(7));
Truncate table student;
insert into student (name, continent) values ('Jane', 'America');
insert into student (name, continent) values ('Pascal', 'Europe');
insert into student (name, continent) values ('Xi', 'Asia');
insert into student (name, continent) values ('Jack', 'America');
Last updated
Was this helpful?