我正在针对 Oracle 10g 数据库编写 SQL 语句。我想获得具有三个不同条件的字段的总和。我可以用一个查询来做到这一点吗?
这是我想要的伪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;
您可以使用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
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