我正在针对Oracle 10g数据库编写SQL语句。我想获得具有三种不同条件的字段的SUM。我可以用一个查询来完成这个吗?
这是我想要的伪SQL:
SELECT SUM(CP) AS CPTotal,
(SUM(CP) FROM tasks WHERE Code='P') AS CPProd,
(SUM(CP) FROM tasks WHERE Code='S') AS CPSupp
FROM tasks;
答案 0 :(得分:2)
您可以使用CASE
条件检查code
。
SELECT SUM(CP) AS CPTotal,
SUM(CASE WHEN Code = 'P' THEN CP END) AS CPProd,
SUM(CASE WHEN Code = 'S' THEN CP END) AS CPSupp
FROM tasks
答案 1 :(得分:2)
可以通过SUM()
语句获得条件CASE
:
SELECT SUM(CP) AS CPTotal,
SUM(CASE WHEN Code = 'P' THEN CP ELSE 0 END) AS CPProd,
SUM(CASE WHEN Code = 'S' THEN CP ELSE 0 END) AS CPSupp
FROM tasks;
如果值与ELSE
语句中的任何条件都不匹配,则NULL
部分不需要CASE
部分,并且在聚合时忽略NULL
,但有些我喜欢把它包括在内。