SQL案例总和

时间:2018-08-07 19:32:05

标签: sql sum case

在长查询中使用SUM时,我很难找出一个案例。这是查询的当前相关部分-

B2

我现在要做的是

SELECT _various items_
SUM (nt.GALLONS) AS "2018 CCE gallons"
FROM MQ_CDS_NETTRAN nt
JOIN MQCCNSTORE s ON nt.COSTCENTER = s.COSTCENTER 
WHERE nt.CLRNTSYS = 'CCE'

,将加仑分别加总为“ 2018 CCE加仑”或“ 2018 BAC加仑”(CLRNTSYS下还有大约8个其他选项,除了“ CCE”或“ BAC”之外)。以前没有使用过CASE,我还没有找到一个示例,您可以根据另一列中的数据求和另一个列并为其命名。那怎么办?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用条件汇总函数。

SELECT _various items_
SUM (CASE WHEN nt.CLRNTSYS ='CCE' THEN nt.GALLONS ELSE 0 END) AS "2018 CCE gallons",
SUM (CASE WHEN nt.CLRNTSYS ='BAC' THEN nt.GALLONS ELSE 0 END) AS "2018 BAC gallons"
FROM MQ_CDS_NETTRAN nt
JOIN MQCCNSTORE s ON nt.COSTCENTER = s.COSTCENTER 
GROUP BY _various items_

答案 1 :(得分:1)

这应该使用conditional aggregation

SELECT _various items_
    SUM (CASE WHEN nt.CLRNTSYS = 'CCE' THEN nt.GALLONS END) AS "2018 CCE gallons",
    SUM (CASE WHEN nt.CLRNTSYS = 'BAC' THEN nt.GALLONS END) AS "2018 BAC gallons"
FROM MQ_CDS_NETTRAN nt
JOIN MQCCNSTORE s ON nt.COSTCENTER = s.COSTCENTER 
WHERE nt.CLRNTSYS IN ('CCE','BAC')