RESET SUM(AMT_FIELD)OVER(按唯一字段排序,按ROWNUM排序)

时间:2018-06-25 03:21:56

标签: sql oracle window-functions

我只是想知道,如何在下面的SQL查询中重置数字字段的总和。

附带的屏幕截图是我需要获取的结果示例。

使用的查询:

SUM(UNPAID_MONTHLY) OVER(PARTITION BY SAMPLE_ACCT ORDER BY MONTH_NO DESC) TOTAL_UNPAID_AMT

enter image description here

2 个答案:

答案 0 :(得分:1)

每次值零时,都需要重置总和。您可以使用累计和定义组,然后再使用另一个累计和:

select t.*,
       sum(unpaid_monthly) over (partition by sample_acct, grp order by month_no desc)
from (select t.*,
             sum(case when unpaid_monthly = 0 then 1 else 0 end) over (partition by sample_acct order by month_no) as grp
      from t
     ) t;

答案 1 :(得分:0)

您还可以使用MATCH_RECOGNIZE子句(如果运行Oracle 12或更高版本):

WITH t (unpaid_monthly, sample_acct, month_no) AS 
    (SELECT 1335.67, 22900005, 1 FROM dual UNION ALL
    SELECT 1289.36, 22900005, 2 FROM dual UNION ALL
    SELECT 1241.95, 22900005, 3 FROM dual UNION ALL
    SELECT 1211.32, 22900005, 4 FROM dual UNION ALL
    SELECT 1179.33, 22900005, 5 FROM dual UNION ALL
    SELECT 0, 22900005, 6 FROM dual UNION ALL
    SELECT 5509.8, 22900005, 7 FROM dual UNION ALL
    SELECT 3388.59, 22900005, 8 FROM dual UNION ALL
    SELECT 1398.41, 22900005, 9 FROM dual UNION ALL
    SELECT 0, 22900005, 10 FROM dual UNION ALL
    SELECT 1717.97, 22900005, 11 FROM dual UNION ALL
    SELECT 0, 22900005, 12 FROM dual UNION ALL
    SELECT 5016.4, 22900005, 13 FROM dual)
SELECT unpaid_monthly, sample_acct, month_no, 
    sum_unpaid + unpaid_monthly AS TOTAL_UNPAID_AMT
FROM t
MATCH_RECOGNIZE (
    PARTITION BY sample_acct
    ORDER BY month_no
    MEASURES 
        FINAL SUM(unpaid_monthly) - SUM(unpaid_monthly) AS sum_unpaid
    ALL ROWS PER MATCH
    PATTERN (a+ b?)
    DEFINE
        a AS unpaid_monthly > 0);


UNPAID_MONTHLY  SAMPLE_ACCT MONTH_NO    TOTAL_UNPAID_AMT
=============================================================
1335.67         22900005    1            6257.63
1289.36         22900005    2            4921.96
1241.95         22900005    3            3632.6
1211.32         22900005    4            2390.65
1179.33         22900005    5            1179.33
0               22900005    6            0
5509.8          22900005    7            10296.8
3388.59         22900005    8            4787
1398.41         22900005    9            1398.41
0               22900005    10           0
1717.97         22900005    11           1717.97
0               22900005    12           0
5016.4          22900005    13           5016.4