我有2个表,学生表,其中包含 regNo 和 name 列;和 reg_subject 表,其中包含学生单独注册的科目列表。一个学生可以注册多个科目。
我想生成一个将两个表连接起来的表,以便将 reg_subject 表转置,使行变成列。 下面概述了这两个表以及结果表。
学生桌
| regNo | name |
_________________
| 1001 | Saleh |
-----------------
| 1002 | Moses |
-----------------
| 1003 | Hafsa |
reg_subject表
| regNo | subject |
____________________
| 1001 | English |
--------------------
| 1001 | Math |
--------------------
| 1002 | English |
--------------------
| 1003 | Math |
--------------------
| 1002 | Math |
--------------------
| 1003 | Physics |
--------------------
| 1001 | Physics |
--------------------
| 1002 | Physics |
--------------------
转置的联接表应如下所示:
The transposed joint table
| regNo | name | subject1 | subject2 | subject3 |
__________________________________________________
| 1001 | Saleh | English | Math | Physics |
--------------------------------------------------
| 1002 | Moses | English | Math | Physics |
--------------------------------------------------
| 1003 | Hafsa | | Math | Physics |
--------------------------------------------------
答案 0 :(得分:0)
SELECT regNo, name,
MAX( CASE WHEN subject = 'English'
THEN subject
END) as subject1,
MAX( CASE WHEN subject = 'Math'
THEN subject
END) as subject2,
MAX( CASE WHEN subject = 'Physics'
THEN subject
END) as subject3
FROM YourTable
GROUP BY regNo, name