一个SQL查询参数中的SUM和MINUS

时间:2019-03-28 14:42:43

标签: sql oracle sum case-when subtraction

我有一个有效的Oracle SQL查询,必须对其进行更改,但不确定如何进行。查询如下:

SELECT
  USERID,
  SUM(CONTAINERS),
  SUM(QTYMISTINT),
  SUM(QTYXMISTINT),
  SUM(CASE WHEN (BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
           THEN GALLONS ELSE 0 END) AS Dispensed2018,
  SUM(CASE WHEN (BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
           THEN GALSMISTINT ELSE 0 END) AS Mistints2018
FROM MQ_CDS_NETTRAN 
WHERE STORENBR = 1564
  AND TRANCODE IN ('DISP','MIST')
GROUP BY USERID
ORDER BY USERID;

我需要做的是关于参数

(BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
THEN GALSMISTINT ELSE 0 END) AS Mistints2018

我需要从该字段中减去一个数量:我需要对另一个字段GALSXMISTINT进行求和,然后从Mistints2018中减去GALSXMISTINT以获得最终结果NetGalsMistint2018。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您也许可以有条件求和:

SELECT
    USERID,
    SUM(CONTAINERS),
    SUM(QTYMISTINT),
    SUM(QTYXMISTINT),
    SUM(CASE WHEN BOOKDATE BETWEEN '01-JAN-18' AND '31-DEC-18'
             THEN GALLONS ELSE 0 END) AS Dispensed2018,
    SUM(CASE WHEN BOOKDATE BETWEEN '01-JAN-18' AND '31-DEC-18'
             THEN GALSMISTINT ELSE 0 END) AS Mistints2018,
    SUM(CASE WHEN BOOKDATE BETWEEN '01-JAN-18' AND '31-DEC-18'
             THEN GALSMISTINT - GALSXMISTINT ELSE 0 END) AS NetGalsMistint2018
FROM MQ_CDS_NETTRAN 
WHERE
    STORENBR = 1564 AND TRANCODE IN ('DISP','MIST')
GROUP BY
    USERID
ORDER BY
    USERID;

答案 1 :(得分:1)

不确定您的确切要求,但是这里有一个左列连接到列总和的子查询的示例。

SELECT
  USERID,
  SUM(CONTAINERS),
  SUM(QTYMISTINT),
  SUM(QTYXMISTINT),
  SUM(CASE WHEN (BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
           THEN GALLONS ELSE 0 END) AS Dispensed2018,
  SUM(CASE WHEN (BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
           THEN GALSMISTINT ELSE 0 END) AS Mistints2018,
  SUM(CASE WHEN (BOOKDATE >= '01-JAN-18' AND BOOKDATE <= '31-DEC-18')
           THEN GALSMISTINT ELSE 0 END) - x.SUM_GAL AS NetGalsMistint2018
FROM MQ_CDS_NETTRAN 
LEFT JOIN ( SELECT USERID, SUM(GALSXMISTINT) AS SUM_GAL 
            FROM MQ_CDS_NETTRAN
            GROUP BY USERID
) x ON X.USERID = MQ_CDS_NETTRAN.USERID
WHERE STORENBR = 1564
  AND TRANCODE IN ('DISP','MIST')
GROUP BY USERID
ORDER BY USERID;