要求:写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。
一所美国大学有来自亚洲、欧洲和美洲的学生,他们的地理信息存放在如下 student 表中。
Student表:
| name | continent |
|--------|-----------|
| Jack | America |
| Pascal | Europe |
| Xi | Asia |
| Jane | America |
Result Table:
| America | Asia | Europe |
|---------|------|--------|
| Jack | Xi | Pascal |
| Jane | null |null |
分析:
1.首先找出学生最多的大洲,查找该大洲的学生姓名,通过自定义变量为每个姓名赋予一个自增的id,为id建立一个临时表
2.将每个大洲查询的姓名通过自定义变量新增一列自增的id列,并通过姓名升序,作为不同的姓名表
3.将临时表与姓名表通过id左连接,求出最终结果
SQL语句:
WITH b AS(
SELECT @a:=@a+1 AS id
FROM student,(SELECT @a:=0)a
WHERE continent=
(SELECT continent
FROM student
GROUP BY continent
ORDER BY COUNT(*) DESC
LIMIT 1))
SELECT America,Asia,Europe
FROM b
LEFT JOIN (SELECT @b:=@b+1 AS id,NAME AS America FROM (SELECT @b:=0)b1,student
WHERE continent='America' order by America)c
ON b.id=c.id
LEFT JOIN (SELECT @c:=@c+1 AS id,NAME AS Asia FROM (SELECT @c:=0)c1,student
WHERE continent='Asia' order by Asia)d
ON b.id=d.id
LEFT JOIN (SELECT @d:=@d+1 AS id,NAME AS Europe FROM (SELECT @d:=0)d1,student
WHERE continent='Europe' order by Europe)e
ON b.id=e.id;