将行转换为列并计算总和
Posted
技术标签:
【中文标题】将行转换为列并计算总和【英文标题】:Convert rows to columns and calculate sum 【发布时间】:2020-11-11 09:00:33 【问题描述】:我有这个
我想要这个
但我得到了这个
我的查询是
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。 我将永远感激任何/所有帮助。谢谢!
【问题讨论】:
【参考方案1】:您需要将 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
【讨论】:
以上是关于将行转换为列并计算总和的主要内容,如果未能解决你的问题,请参考以下文章