如何计算SUM值之间的差异

时间:2015-04-28 17:29:34

标签: sql teradata difference

我提取各个日期的总帐户余额,需要计算这些帐户总余额之间的差异,但需要解决方案。

SQL:

SELECT SNAPSHOT_DATE,
SUM(ACCOUNT_BALANCE_AMOUNT) SAVINGS_BALANCES
FROM pIDWUserVW.PRODUCT_SAVINGS_VW
WHERE SNAPSHOT_DATE IN ('2015-01-02',  '2015-01-30', '2015-02-02', '2015-02-27', '2015-03-31')
GROUP BY SNAPSHOT_DATE
ORDER BY SNAPSHOT_DATE ASC;

结果:

SNAPSHOT_DATE   SAVINGS_BALANCES
1/2/2015    10,407,069,092.55
1/30/2015   10,581,034,604.38
2/2/2015    10,525,024,786.77
2/27/2015   11,105,597,533.96
3/31/2015   11,371,511,747.20

这是我想要的(“差异”栏目),但我找不到合适的功能来执行此操作:

SNAPSHOT_DATE   SAVINGS_BALANCES    DIFFERENCE
1/2/2015    10,407,069,092.55   
1/30/2015   10,581,034,604.38   173,965,511.83 
2/2/2015    10,525,024,786.77   (56,009,817.61)
2/27/2015   11,105,597,533.96   580,572,747.19 
3/31/2015   11,371,511,747.20   265,914,213.24 

我正在使用Teradata SQL Assistant并且当我尝试像MDIFF这样的函数但是我可能做错了时,会出现仅允许使用窗口函数的错误。

1 个答案:

答案 0 :(得分:1)

窗口聚合函数是聚合后计算的,您需要一个LEAD函数,该函数未在Teradata中实现,但可以轻松模拟:

SELECT SNAPSHOT_DATE,
   SUM(ACCOUNT_BALANCE_AMOUNT) SAVINGS_BALANCES,
   SUM(ACCOUNT_BALANCE_AMOUNT)        -- current value
   - MIN(SUM(ACCOUNT_BALANCE_AMOUNT)) -- previous row's value
     OVER (ORDER BY SNAPSHOT_DATE
           ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS DIFFERENCE
FROM pIDWUserVW.PRODUCT_SAVINGS_VW
WHERE SNAPSHOT_DATE IN ('2015-01-02',  '2015-01-30', '2015-02-02', '2015-02-27', '2015-03-31')
GROUP BY SNAPSHOT_DATE
ORDER BY SNAPSHOT_DATE ASC;