我有以下结果集,它是两个连接表的结果,我想使用子查询重新定向结果。这是当前结果集的示例,它是动态记录数:
Forename Surname Subject Result
Mercury Freddie English C
Mercury Freddie Mathematics D
Simon Paul English E
Simon Paul Mathematics F
Garfunkle Art English A
Garfunkle Art Mathematics B
这就是我想要实现的目标:
Forename Surname English Mathematics
Mercury Freddie C D
Simon Paul E F
Garfunkle Art A B
我尝试使用 case 语句来填充它,但这会导致以下结果:
Forename Surname English Mathematics
Mercury Freddie NULL
Simon Paul NULL
Garfunkle Art NULL
Mercury Freddie C NULL
Simon Paul E NULL
Garfunkle Art A NULL
你可以
使用CASE
,你只需要将它与一些聚合函数(如MAX()
和GROUP BY
SELECT
Forename, Surname
, MAX(CASE WHEN SUBJECT = 'English' THEN Result END) AS English
, MAX(CASE WHEN SUBJECT = 'Mathematics' THEN Result END) AS Mathematics
FROM Table1
GROUP BY Forename, Surname
SQLFiddle DEMO