使用GROUP BY执行SELECT COUNT时也选择零值

时间:2013-10-21 10:58:14

标签: sql postgresql aggregate-functions generate-series

我正在创建统计模块。我的工作之一是创建过去一周注册用户总数的情节 问题是我的服务只有少数客户使用,所以很多时候没有人注册。

表格描述(简化)是:

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"

1 个答案:

答案 0 :(得分: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