欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > SQL,力扣题目618,学生地理信息报告

SQL,力扣题目618,学生地理信息报告

2025/10/18 16:51:41 来源:https://blog.csdn.net/m0_59659684/article/details/143633898  浏览:    关键词:SQL,力扣题目618,学生地理信息报告

一、力扣链接

LeetCode_618

二、题目描述

表: student 

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

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

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

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

三、目标拆解

四、建表语句

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

五、过程分析

1、添加排序字段作为分组字段

2、行转列

六、代码实现

with t1 as(select name, continent, row_number() over (partition by continent order by name) rn from student  -- 这里order by为满足目标2,rn为行转列做准备
)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 Europefrom t1
group by rn;

七、结果验证

八、小结

1、典型的行转列,分组解法

2、case when + group by + max()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词