我正在尝试创建一个看起来像这样的表(过去12个月的表)
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
我的代码看起来像这样:
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个工会?
答案 0 :(得分:3)
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
;