0

我正在针对 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;
4

2 回答 2

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
于 2013-09-24T19:28:48.860 回答
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部分不需要作为结果,并且在聚合时被忽略,但有些人更喜欢包含它。NULLCASENULL

于 2013-09-24T19:29:13.120 回答