LeetCode_sql_day19(618.学生地理信息报告)

描述:

表: student 

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| name        | varchar |
| continent   | varchar |
+-------------+---------+
该表可能包含重复的行。
该表的每一行表示学生的名字和他们来自的大陆。

一所学校有来自亚洲、欧洲和美洲的学生。

编写解决方案实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。

测试用例的生成保证来自美国的学生人数不少于亚洲或欧洲的学生人数。

返回结果格式如下所示。

示例 1:

输入: 
Student table:
+--------+-----------+
| name   | continent |
+--------+-----------+
| Jane   | America   |
| Pascal | Europe    |
| Xi     | Asia      |
| Jack   | America   |
+--------+-----------+
输出: 
+---------+------+--------+
| America | Asia | Europe |
+---------+------+--------+
| Jack    | Xi   | Pascal |
| Jane    | null | null   |
+---------+------+--------+

进阶:如果不能确定哪个大洲的学生数最多,你可以写出一个查询去生成上述学生报告吗?

数据准备:

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')

分析:

①先根据continent分组 求排名

select * ,row_number() over (partition by continent)rn from Student 

②通过观察结果输出,分别对America、Asia、Europe三个州判断 ,最后用max包裹一下,并且根据排名进行分组

select
    max(case when  continent='America' then name  end) as America,
    max(case when continent='Asia' then name  end) as Asia,
    max(case when continent='Europe' then name  end) as Europe
from t1
group by rn

代码:

with t1  as (
select * ,row_number() over (partition by continent order by name)rn from Student )
select
    max(case when  continent='America' then name  end) as America,
    max(case when continent='Asia' then name  end) as Asia,
    max(case when continent='Europe' then name  end) as Europe
from t1
group by rn;

总结:

max()函数很巧妙的用法,因为分组 所以要使用聚合函数此处也可以用min()

解决了需要先知道哪个大洲人数最多的问题

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值