【发布时间】:2010-09-25 15:48:01
【问题描述】:
我有几年(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)
但他们中的一些人错过了一些间隔,因为没有数据存在,就像这个:
select to_char(date_trunc('month',date), 'YYYY-MM-DD'),count(distinct post_id)
from some_table where category_id=1 and entity_id = 75 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 | 2
2008-01-01 | 2
2008-03-01 | 1
2008-04-01 | 2
2008-06-01 | 1
2008-08-01 | 3
2008-10-01 | 2
(7 rows)
所需的结果集在哪里:
to_char | count
------------+-------
2007-12-01 | 2
2008-01-01 | 2
2008-02-01 | 0
2008-03-01 | 1
2008-04-01 | 2
2008-05-01 | 0
2008-06-01 | 1
2008-07-01 | 0
2008-08-01 | 3
2008-09-01 | 0
2008-10-01 | 2
2008-11-01 | 0
(12 rows)
缺失条目的计数为 0。
我已经看到早期关于 Stack Overflow 的讨论,但它们似乎并没有解决我的问题,因为我的分组期是(日、周、月、季度、年)之一,并由应用程序决定运行时。因此,我猜像左连接与日历表或序列表这样的方法无济于事。
我目前的解决方案是使用日历模块在 Python(在 Turbogears 应用中)填补这些空白。
有没有更好的方法来做到这一点。
【问题讨论】:
标签: python database postgresql left-join generate-series