我正在创建统计模块。我的工作之一是用过去一周的注册用户总数创建绘图。
问题是我从事的服务只有少数客户使用,所以没有人注册的日子经常发生。
表说明(简体)为:
TABLE users:
============
id serial NOT NULL,
date_created timestamp with timezone NOT NULL DEFAULT NOW()
要获得过去 7 天的总和,我使用
SELECT
COUNT(id) as ile,
DATE_TRUNC('day', date_created) as day
FROM
users
WHERE
date_created >= now() - INTERVAL '7 days'
GROUP BY 2
ORDER BY 2
一切正常,Postgres返回例如:
ile | day
===========================
2 | "2013-09-23 00:00:00"
1 | "2013-09-25 00:00:00"
除了它省略了 0 计数的天数。当然,我必须解析此查询的结果(在本例中为:PHP + Symfony),以便我可以遍历所需的日期范围并填充空白,但我想知道是否有简单的方法可以要求PostgreSQL为我完成此操作,因此它返回如下内容:
ile | day
===========================
2 | "2013-09-23 00:00:00"
0 | "2013-09-24 00:00:00"
1 | "2013-09-25 00:00:00"
0 | "2013-09-26 00:00:00"
0 | "2013-09-27 00:00:00"
0 | "2013-09-28 00:00:00"
0 | "2013-09-29 00:00:00"
目前无法测试,但您可以使用 generate_series() 函数:
select
count(u.id) as ile,
d.day
from generate_series('2013-09-23'::date, '2013-09-29'::date, '1d') as d(day)
left outer join users as u on u.date_created >= d.day and u.date_created < d.day + '1d'::interval
-- or left outer join users as u on date_trunc('day', u.date_created) = d.day
-- but I think that >= and < will be faster if you have index on `date_created`
group by d.day