我正在尝试创建一个看起来像这样的表(过去 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 个并集更简洁的写法?
最佳答案
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
;
关于postgresql - 在 Postgresql 中创建最近 12 个月的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345847/