题40:
根据下表写一个查询语句实现对大洲(continent)列的透视表操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出要求标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)
解题思路:这是一个
(1)先是根据洲名分组,对同一洲名的学生进行组内排序编号;
(2)然后分别判断这些学生的所属洲:
- 如果是美洲,则将该学生的名字赋值给美洲,否则置null;
- 如果是亚洲,则将该学生的名字赋值给亚洲,否则置null;
- 如果是欧洲,则将该学生的名字赋值给欧洲,否则置null;
(1)(2)步就实现列转行。注意:m利用max()确保在最大行未知的情况下不遗漏行。
(3)接下来需要将列转行的结果根据编号整合一下,然后将这些记录根据排序的编号分组。
select
max(case when continent = 'America' then name else null end) as America,
max(case when continent = 'Asia' then name else null end) as Asia,
max(case when continent = 'Europe' then name else null end) as Europe
from
(
select *, row_number() over (partition by continent order by name) rk
from student
) t
group by rk;