2016-10-31 37 views
1

我試圖創建一個表,看起來像這樣(過去12個月的表)在PostgreSQL

month, year 
10, 2016 
9, 2016 
8, 2016 
7, 2016 
6, 2016 
5, 2016 
4, 2016 
3, 2016 
2, 2016 
1, 2016 
12, 2015 
11, 2015 

我的代碼看起來像這樣創建過去12個月的表:

select date_part('month', current_date) as order_month, 
select date_part('year', current_date) as order_year 
union all 
select date_part('month', current_date - interval '1 month') as order_month, 
select date_part('year', current_date - interval '1 month') as order_year 
union all 
... 

有沒有更簡潔的寫作方式,而不是使用11個聯合?

+1

也許http://stackoverflow.com/q/7450515/1741542或http://stackoverflow.com/q/14113469/1741542幫助。 –

回答

2

generate_series(start, stop, step)將是有益的,使得

SELECT 
    EXTRACT('month' FROM d) AS month, 
    EXTRACT('year' FROM d) AS year 
FROM 
    GENERATE_SERIES(
     now(), 
     now() - interval '12 months', 
     interval '-1 month' 
    ) AS d 
;