2012-02-08 41 views
0

編寫一個SQL查詢,該查詢應返回之前91天窗口的平均費用。我將截止日期截至一週的第一天,並預計到今天爲止的91天平均值爲91天前Oracle Analytic Preceding返回錯誤/未預料的結果

但是,在驗證它時,似乎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

+0

如果您有類似於我上面的問題,我強烈建議您查看sheetchqueez頻道的YouTube分析功能概述,http://www.youtube.com/user/sheepsqueezersYT/search ?query = analytic或http://www.sheepsqueezers.com/。 – Cimplicity 2012-02-09 14:40:08

回答

1

我想你想你的窗口子句是:

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

,以排除當前一週的費用。

您可能還想將「91」更改爲「92」,以便在開頭增加一週。

+0

輝煌的這個伎倆。所以我不得不承認,我仍然不明白爲什麼我的查詢是抓住了本週,什麼讓你排除它。如果你有一分鐘​​的時間來解釋這很好。或者隨時向我指出我應該查看的一些文檔。我只是不確定在哪裏看。無論哪種方式......非常感謝! – Cimplicity 2012-02-08 19:10:44

+1

@Cimplicity:你只是給出了一個範圍的起始點。默認終點是當前行,並且它是包含性的。通過明確設置'INTERVAL'1' DAY PRECEDING'的端點,當前行被排除。 – 2012-02-08 19:24:40

0

分割之前減去電流值?

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

我給了這個嘗試,但沒有骰子。它完全改變了數字。現在這些數字是正確的,只是抵消了一週。感謝您的建議,雖然...;) – Cimplicity 2012-02-08 18:40:35