0

我有以下结果集,它是两个连接表的结果,我想使用子查询重新定位结果。这是当前结果集的示例,它是动态记录数:

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
4

1 回答 1

1

你可以使用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 演示

于 2013-10-25T10:22:10.430 回答