RESET SUM(AMT_FIELD) OVER(PARTITION BY UNIQUE FIELD ORDER BY ROWNUM)

Posted

技术标签:

【中文标题】RESET SUM(AMT_FIELD) OVER(PARTITION BY UNIQUE FIELD ORDER BY ROWNUM)【英文标题】: 【发布时间】:2018-06-25 03:21:55 【问题描述】:

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

附件截图是我需要得到的结果样本。

使用的查询:

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

【问题讨论】:

编辑您的问题并提供示例数据和所需结果。 结果数据请不要粘贴图片,使用文字。 【参考方案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;

【讨论】:

【参考方案2】:

您也可以使用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

【讨论】:

以上是关于RESET SUM(AMT_FIELD) OVER(PARTITION BY UNIQUE FIELD ORDER BY ROWNUM)的主要内容,如果未能解决你的问题,请参考以下文章

Jenkins Publish over SSH 异常:Connection reset by peer: socket write error

在mysql中,sum(a)和sum(a) over()有啥区别?

Prometheus之sum_over_time函数

SUM() OVER (PARTITION BY) AS - 存在重复项时

视图中的 SUM(...) OVER (ORDER BY ...) 导致性能不佳

MySQL - SUM() OVER() 函数用法详解