(1)现有学生分数表如下:
mysql> select * from vmark1;
+-----+--------+--------+------+
| sid | sname | course | mark |
+-----+--------+--------+------+
| 1 | 张三 | jsj | 90 |
| 1 | 张三 | yuwen | 65 |
| 1 | 张三 | yingyu | 80 |
| 2 | 李四 | jsj | 80 |
| 2 | 李四 | yuwen | 98 |
| 2 | 李四 | yingyu | 90 |
+-----+--------+--------+------+
6 rows in set (0.00 sec)
(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)
“哇塞,要的就是这效率。别动了。。就这样”。运营妹子激动的说。
好吧。over.
原文地址:http://blog.51cto.com/448823/2113618