Oracle Analytic Preceding 返回错误/意外结果

发布于 2025-01-03 21:57:24 字数 917 浏览 2 评论 0原文

编写一个 SQL 查询,该查询应返回之前 91 天窗口的平均费用。我将日期截断为一周的第一天,并期望 91 天的平均值为该日期之前的 91 天。

然而,在验证时,91 天的平均值似乎包括我截断的本周。

查询:

SELECT
    week AS WEEK,
    to_char(week,'ww-yyyy') AS Week_num
    --Sum of the charges for the previous 91 days / 91 will give you avg charges per day for the last 91 days
    --Need to count days regardless of if there are any charges on that day
    ,(SUM(CHARGES) OVER (ORDER BY WEEK RANGE INTERVAL '91' DAY PRECEDING))/91 MV_91_DAY_AVG
FROM 
( 

    SELECT
         --Truncate date down to first of week. Goal is to make 91 day preceding being at this date.
         TRUNC(TRANS.ORIG_POST_DATE,'WW') AS WEEK
         ,SUM(TRANS.AMOUNT) AS CHARGES
    FROM TRANS
    WHERE
        TRANS.DETAIL = "Charge"
    GROUP BY TRUNC(TRANS.ORIG_POST_DATE,'WW')
)
ORDER BY WEEK

当前输出: 在此处输入图像描述

Writing a SQL query that should return the average charges for a preceding 91 day window. I truncate the date down to the first day of the week and expect the 91 day average to be the 91 days prior to this date.

However when validating it appears that the 91 day average is including the current week that I truncated.

Query:

SELECT
    week AS WEEK,
    to_char(week,'ww-yyyy') AS Week_num
    --Sum of the charges for the previous 91 days / 91 will give you avg charges per day for the last 91 days
    --Need to count days regardless of if there are any charges on that day
    ,(SUM(CHARGES) OVER (ORDER BY WEEK RANGE INTERVAL '91' DAY PRECEDING))/91 MV_91_DAY_AVG
FROM 
( 

    SELECT
         --Truncate date down to first of week. Goal is to make 91 day preceding being at this date.
         TRUNC(TRANS.ORIG_POST_DATE,'WW') AS WEEK
         ,SUM(TRANS.AMOUNT) AS CHARGES
    FROM TRANS
    WHERE
        TRANS.DETAIL = "Charge"
    GROUP BY TRUNC(TRANS.ORIG_POST_DATE,'WW')
)
ORDER BY WEEK

Current output:
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

弄潮 2025-01-10 21:57:24

我认为您希望您的窗口条款是:

(ORDER BY WEEK RANGE BETWEEN INTERVAL '91' DAY PRECEDING AND INTERVAL '1' DAY PRECEDING)

为了排除本周的费用。

您可能还需要将“91”更改为“92”,以在开始时添加额外的一周。

I think you want your window clause to be:

(ORDER BY WEEK RANGE BETWEEN INTERVAL '91' DAY PRECEDING AND INTERVAL '1' DAY PRECEDING)

in order to exclude the current week's charges.

You may also want to change the '91' to '92' to include an additional week at the beginning.

烟酒忠诚 2025-01-10 21:57:24

除法之前先减去当前值?

,(SUM(CHARGES) OVER (ORDER BY WEEK RANGE INTERVAL '91' DAY PRECEDING) - CHARGES)/91

Subtract the current value before dividing?

,(SUM(CHARGES) OVER (ORDER BY WEEK RANGE INTERVAL '91' DAY PRECEDING) - CHARGES)/91
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文