如何在MySQL中将行转换为列?

时间:2018-06-24 07:24:08

标签: mysql mysqli

我有三个表(学生的信息,主题和分数):

这是餐桌学生的信息:

----------------
|s_id | s_name |
----------------
| 1 | Ali      |
| 2 | Jon      |
---------------

这是表格主题:

 ----------------
|sub_id | subject|
----------------
| 1   | Word     |
| 2   | Windows  |
| 3   | Excel    |
-----------------

这是表格标记:

 --------------------------
|id | s_id |sub_id|n_marks|
---------------------------
| 1 |  1   |  1   |  50   |
| 2 |  1   |  2   |  44   | 
| 3 |  1   |  3   |  90   |
| 4 |  2   |  1   |  32   |
| 5 |  2   |  2   |  56   |
| 6 |  2   |  3   |  66   |
--------------------------

我使用以下代码将行作为列转置:

SELECT 
students_info.*,marks.*,
CASE WHEN subject = 'Word' THEN marks.n_mark ELSE 0 END AS `Word`,
CASE WHEN subject = 'Windows' THEN marks.n_mark ELSE 0 END AS `Windows`,
CASE WHEN subject = 'Excel' THEN marks.n_mark ELSE 0 END AS `Excel`

FROM students_info
INNER JOIN marks ON students_info.s_id = marks.s_id
INNER JOIN subjects ON marks.sub_id = subjects.sub_id
GROUP BY students_info.s_name;

我不想自己在代码中编写主题表,因为主题表中有名称主题,所以我需要一个代码来选择名称主题。

感谢任何能帮助我的人...

0 个答案:

没有答案