0

我正在创建统计模块。我的工作之一是用过去一周的注册用户总数创建情节。
问题是我从事的服务只有少数客户使用,所以经常发生没有人注册的日子。

表描述(简化)是:

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"
4

1 回答 1

1

目前无法测试,但您可以使用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
于 2013-10-21T11:48:28.450 回答