MySQL Demand Scenario - Column to Row

Since it is a simulated scene, it goes straight to the topic, and the table name and structure definition are very low, please ignore it!

(1) The existing student score table is as follows:
mysql> select * from vmark1;
+-----+--------+--------+------+
| sid | sname | course | mark |
+-----+--------+--------+------+
| 1 | Zhang San | jsj | 90 |
| 1 | Zhang San | yuwen | 65 |
| 1 | Zhang San | yingyu | 80 |
| 2 | Li Si | jsj | 80 |
| 2 | Li Si
|
+-----+--------+--------+------+
6 rows in set (0.00 sec)

(2) The requirement is to view students' grades in a more intuitive way. Refinement is to display the value of the mark column in the form of a row. Query by case..when statement:
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 | Zhang San| 90 | NULL | NULL |
| 1 | Zhang San | NULL | 65 | NULL | |
1 | Zhang San | NULL | NULL | 98 | NULL | | 2 | Li Si | NULL | NULL | 90 | +-----+--------+------+-------+--- -----+ 6 rows in set (0.01 sec)




I rely on, become OK. But it still looks very unfriendly!

(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)

"Wow, that's what I want. Don't move...that's all." The operation girl said excitedly.

All right. over.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325674308&siteId=291194637