我有不均匀分布的数据(wrt日期)几年(2003-2008).我想查询一组给定的开始和结束日期的数据,按PostgreSQL 8.3中任何支持的时间间隔(日,周,月,季,年)对数据进行分组(http://www.postgresql.org/docs /8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC).
问题是某些查询会在所需的时间段内提供连续的结果,如下所示:
select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id)
from some_table where category_id=1 and entity_id = 77 and entity2_id = 115
and date <= '2008-12-06' and date >= '2007-12-01' group by
date_trunc('month',date) order by date_trunc('month',date);
to_char | count
------------+-------
2007-12-01 | 64
2008-01-01 | 31
2008-02-01 | 14
2008-03-01 | 21
2008-04-01 | 28
2008-05-01 | 44
2008-06-01 | 100
2008-07-01 | 72
2008-08-01 | 91
2008-09-01 | 92
2008-10-01 | 79
2008-11-01 | 65
(12 rows)
Run Code Online (Sandbox Code Playgroud)
但有些人因为没有数据而错过了一些间隔,因为这个:
select …Run Code Online (Sandbox Code Playgroud)