Oracle Analytic Preceding返回错误/未预料到的结果

时间:2012-02-08 18:07:04

标签: sql oracle date analytics

编写一个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

当前输出: enter image description here

2 个答案:

答案 0 :(得分:1)

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

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

以排除当前一周的费用。

您可能还想将“91”更改为“92”,以便在开头添加一周。

答案 1 :(得分:0)

在除以之前减去当前值?

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