我想计算前三个月余额的总和。我正在尝试遵循以下代码,但无法正常工作。你能帮忙吗
我的数据集
DATE ID BAL
201701 1 1004768.32
201702 2 1126215.77
201703 3 1135731.08
201704 4 1383859.84
201705 5 1828847.51
201706 6 1520265.46
下面是我用来计算SUM_PREV_3_MNTH_BAL的SQL。但是,问题是我之前的3个月未获得补偿,但不是总和
ROUND(LAG(SUM(BAL), 3) over (partition by ID order by DATE),2) AS SUM_PREV_3_MNTH_BAL.
我也尝试了以下方法,
ROUND(SUM(lag(BAL,3)) over (partition by ID order by DATE),2) AS SUM_PREV_3_MNTH_BAL-- which is getting below error
ORA-30484: missing window specification for this function
30484. 00000 - "missing window specification for this function"
*Cause: All window functions should be followed by window specification,
like <function>(<argument list>) OVER (<window specification>)
以下是我得到的错误结果。
DATE ID BAL SUM_PREV_3_MNTH_BAL -- incorrect
201701 1 1004768.32
201702 2 1126215.77
201703 3 1135731.08
201704 4 1383859.84 1004768.32
201705 5 1828847.51 1126215.77
201706 6 1520265.46 1135731.08
我的预期结果如下
DATE ID BAL SUM_PREV_3_MNTH_BAL--correct
201701 1 1004768.32
201702 2 1126215.77
201703 3 1135731.08
201704 4 1383859.84 3266715.17
201705 5 1828847.51 3645806.69
201706 6 1520265.46 4348438.43
答案 0 :(得分:1)
您应该将SUM
用作分析函数,并在此处使用适当的窗口:
SELECT
"DATE",
ID,
BAL,
CASE WHEN LAG(BAL, 3) OVER (ORDER BY "DATE") IS NOT NULL
THEN SUM(BAL) OVER (ORDER BY "DATE" ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING)
ELSE NULL END AS SUM_PREV_3_MNTH_BAL
FROM yourTable
ORDER BY
ID;
我们首先检查3个月前表中是否存在余额。如果不是,那么我们只报告这三个月的金额NULL
(这种情况发生在2017年1月至3月)。如果余额存在存在,那么我们取3个月的总和。请注意,我们在此使用的窗口在前面的3至1行之间。