表: 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 |
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/students-report-by-geography
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
步骤:先打标签再group by再case when
group by rk:可以把同一个洲的人分为不同的组
select
max(case when continent='America' then name else null end) America,
max(case when continent='Asia' then name else null end) Asia,
max(case when continent='Europe' then name else null end) Europe
from (select *,
row_number() over(partition by continent order by name) rk
from student
) t
group by rk