将行转换为列并计算总和

Convert rows to columns and calculate sum

我有这个

我想要这个

但我得到的是这个

我的查询是

SELECT   SID, 
         NAME, 
         SUBJECT, ( 
         CASE 
                  WHEN EXAMTYPE IN ('ASSIGNMENTS', 
                                    'PRACTICAL') THEN SUM(MARKS) 
                  ELSE 0 
         END) AS "ASSIGNMENTS + PRACTICAL", ( 
         CASE 
                  WHEN EXAMTYPE = 'WRITTEN' THEN SUM(MARKS) 
                  ELSE 0 
         END) AS "WRITTEN"
FROM     MARKSHEET 
WHERE    EXAMTYPE IN ('ASSIGNMENTS', 
                      'PRACTICAL', 
                      'WRITTEN') 
GROUP BY SID, 
         NAME, 
         SUBJECT, 
         EXAMTYPE

我正在使用 IBM DB2。 我将永远感激 any/all 的帮助。谢谢!

您需要将 case 表达式放入 sum() - 如 sum(case when...) 此外,从 group by clause

中删除 examType 字段
SELECT   SID, 
         NAME, 
         SUBJECT, sum( 
         CASE 
                  WHEN EXAMTYPE IN ('ASSIGNMENTS', 
                                    'PRACTICAL') THEN MARKS 
                  ELSE 0 
         END) AS "ASSIGNMENTS + PRACTICAL", ( 
         sum(CASE 
                  WHEN EXAMTYPE = 'WRITTEN' THEN MARKS
                  ELSE 0 
         END) AS "WRITTEN"
FROM     MARKSHEET 
WHERE    EXAMTYPE IN ('ASSIGNMENTS', 'PRACTICAL', 'WRITTEN') 
GROUP BY SID, NAME, SUBJECT