(2)需求是以更直观的方式,查看学生的成绩。细化也就是把mark这列的值,以行的形式展示。通过case..when语句查询: mysql> select sid,sname,case when course='jsj' then mark end jsj,case when course='yuwen' then mark end yuwen,case when course='yingyu' then mark end yingyu from vmark1; +-----+--------+------+-------+--------+ | sid | sname | jsj | yuwen | yingyu | +-----+--------+------+-------+--------+ | 1 | 张三 | 90 | NULL | NULL | | 1 | 张三 | NULL | 65 | NULL | | 1 | 张三 | NULL | NULL | 80 | | 2 | 李四 | 80 | NULL | NULL | | 2 | 李四 | NULL | 98 | NULL | | 2 | 李四 | NULL | NULL | 90 | +-----+--------+------+-------+--------+ 6 rows in set (0.01 sec)
我靠,变成行了。但看起来依然很不友好!
(3)通过函数和group by字句优化: mysql> select sid,sname,sum(case when course='jsj' then mark end) jsj,sum(case when course='yuwen' then mark end) yuwen,sum(case when course='yingyu' then mark end) yingyu from vmark1 group by sid; +-----+--------+------+-------+--------+ | sid | sname | jsj | yuwen | yingyu | +-----+--------+------+-------+--------+ | 1 | 张三 | 90 | 65 | 80 | | 2 | 李四 | 80 | 98 | 90 | +-----+--------+------+-------+--------+ 2 rows in set (0.00 sec)