在Postgresql中生成一系列的季度

Tom*_*eif 6 postgresql postgresql-9.1

在开始日期和结束日期之前,我需要生成一系列季度.我知道generate_series(),但它不适用于quarter:

SELECT * FROM generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 quarter');
Run Code Online (Sandbox Code Playgroud)

是什么让季度如此特别?除此以外generate_series()可以使用几乎所有东西,从微秒到千禧年:

select * from generate_series('2008-01-01 00:00'::timestamp,'2008-01-01 00:00:00.001', '1 microsecond');
select * from generate_series('2008-01-01 00:00'::timestamp,'2008-01-01 00:01', '1 second');
select * from generate_series('2008-01-01 00:00'::timestamp,'2008-01-01 01:00', '1 minute');
select * from generate_series('2008-01-01 00:00'::timestamp,'2008-01-01 12:00', '1 hour');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 day');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 week');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 month');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 year');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 decade');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 century');
select * from generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 millennium');
Run Code Online (Sandbox Code Playgroud)

如果quarter不能使用那么最好的其他选择是什么?现在,我有:

select 
   date_trunc('quarter',generate_series) gs 
from 
   generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 month') 
group by 
   gs
order by
   gs;
Run Code Online (Sandbox Code Playgroud)

Dan*_*ité 11

不应该这样做你期望的:

SELECT * FROM generate_series('2008-01-01 00:00'::timestamp,
                              '2009-01-01 12:00', '3 months');
Run Code Online (Sandbox Code Playgroud)

结果:

   generate_series   
---------------------
 2008-01-01 00:00:00
 2008-04-01 00:00:00
 2008-07-01 00:00:00
 2008-10-01 00:00:00
 2009-01-01 00:00:00
(5 rows)

  • 意识到这是一个古老的答案,但我最近遇到了这个。将 date_trunc('quarter', your_date) 添加到您的开始日期将保证您从季度初开始。`SELECT * FROMgenerate_series(date_trunc('季度', '2008-02-01 00:00'), '2009-01-01 12:00', '3 个月');` (2认同)