从另一个日期的总和中减去一个日期的流量总和?

时间:2015-11-02 20:41:36

标签: sql oracle date sum

我需要帮助找出如何编写一个查询,该查询将在两个特定日期查找我的Flow的SUM值,并从另一个中减去一个。

基本上我需要找到2015年10月30日流量的总和,并在12/31/2014的流量总和中减去它,以便获得年初至今的变化。下面的查询是我到目前为止的。它确切地给了我特定日期所需要的东西,但是现在我需要能够运行计算以获得YTD。

SELECT * 
FROM (SELECT NAME, SUM(FLOWS/1000000.00) AS FLOWS
FROM HISTORY_TBL1
WHERE DATE = TO_DATE('10302015','MMDDYYYY')
GROUP BY NAME
ORDER BY FLOWS DESC)
WHERE ROWNUM <=10

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合来获取这两个值及其差异:

SELECT NAME,
       SUM(CASE WHEN DATE = DATE '2014-12-31' THEN FLOWS END)/1000000.00 AS FLOWS_20141231,
       SUM(CASE WHEN DATE = DATE '2015-10-30' THEN FLOWS END)/1000000.00 AS FLOWS_20151030,
       SUM(CASE WHEN DATE = DATE '2015-10-30' THEN FLOWS
                WHEN DATE = DATE '2014-12-31' THEN - FLOWS
           END)/1000000.00 AS FLOWS_DIFF,
FROM HISTORY_TBL1
WHERE DATE IN (DATE '2015-10-30',  DATE '2014-12-31')
GROUP BY NAME;

我不确定你想要对结果做些什么。

答案 1 :(得分:0)

SELECT NAME,
       SUM(
          CASE 
          WHEN DATE=TO_DATE('10302015','MMDDYYYY') THEN FLOWS    -- the bigger number
          WHEN DATE=TO_DATE('12312014','MMDDYYYY') THEN FLOWS * -1 -- minus the smaller number
          ELSE 0 
          END
       )/1000000.00 AS FLOWS_2015_minus_2014
FROM HISTORY_TBL1
WHERE DATE IN ( TO_DATE('10302015','MMDDYYYY'),
        TO_DATE('12312014','MMDDYYYY'))
GROUP BY NAME;