在Postgresql中生成一系列的季度

时间:2013-06-28 12:56:10

标签: postgresql postgresql-9.1

我需要根据开始日期和结束日期生成一系列季度。我知道generate_series(),但它只适用于quarter

SELECT * FROM generate_series('2008-01-01 00:00'::timestamp,'2009-01-01 12:00', '1 quarter');

是什么让季度如此特别?否则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');

如果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;

1 个答案:

答案 0 :(得分:9)

这不应该符合您的期望:

SELECT * FROM generate_series('2008-01-01 00:00'::timestamp,
                              '2009-01-01 12:00', '3 months');

结果:

   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)