如何计算 SUM 值之间的差异

How to calculate the Difference between SUM values

我正在提取不同日期的总账户余额,需要计算这些总账户余额之间的差异,但需要解决方案。

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

这是我想要的("Difference" 列),但我找不到合适的函数来执行此操作:

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 并遇到错误,例如 Aggregates are allowed only with Window Functions 当我尝试像 MDIFF 这样的函数时,但我可以做错了。

Windowed Aggregate Function 计算 after aggregation,您需要一个 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;