2016-05-05 51 views
0

我有一個遞歸查詢,它提供了上週(week_no,week_start和week_end)上星期放置的訂單數量。我想爲月份分析創建一個類似的分類。將遞歸查詢從上週的週轉換爲上月的月

WITH recursive weeks (week_start, week_end, time_end, weekno) AS (
VALUES ('2015-12-27'::date, '2016-01-02'::date, '2016-04-02'::date, 1) 
UNION ALL 
SELECT (week_end + interval '1 day')::date, 
     (CASE 
       WHEN (week_end + interval '7 days')::date > time_end THEN time_end 
       ELSE (week_end + interval '7 days')::date 
     END)::date, 
     time_end, 
     weekno+1 
FROM weeks 
WHERE time_end > week_end) 

任何幫助將不勝感激。

回答

1

爲什麼你會爲此使用遞歸查詢?使用generate_series()

select g.week_start, g.week_start + interval '6 day' as week_end, 
     row_number() over (order by g.week_start) as weeknum 
from generate_series('2015-12-27'::timestamp, 
        '2016-01-02'::timestamp, 
        interval '1 week' 
        ) g(week_start); 

相當於幾個月會是這樣:

select g.month_start, g.month_start + interval '1 month' - interval '1 day' as month_end, 
     row_number() over (order by g.month_start) as monthnum 
from generate_series('2015-12-01'::timestamp, 
        '2016-01-01'::timestamp, 
        interval '1 month' 
        ) g(month_start);