我写了一个查询来检索我每天有多少网站注册:
SELECT created, COUNT(id)
FROM signups
GROUP BY created
ORDER BY created desc
但是,这只检索人们实际注册的天数的行。如果一天没有人注册,我想当天返回 0。有没有办法使用 SQL 来做到这一点,还是我必须使用 PHP 解析结果?
我写了一个查询来检索我每天有多少网站注册:
SELECT created, COUNT(id)
FROM signups
GROUP BY created
ORDER BY created desc
但是,这只检索人们实际注册的天数的行。如果一天没有人注册,我想当天返回 0。有没有办法使用 SQL 来做到这一点,还是我必须使用 PHP 解析结果?
由于缺乏信息,假设created
是类型。date
Postgres 提供了generate_series()
使这一切变得容易的美妙方法:
SELECT d.created, COUNT(s.id) AS ct
FROM (
SELECT generate_series(min(created)
, max(created), interval '1 day')::date AS created
FROM signups
) d
LEFT JOIN signups s USING (created)
GROUP BY 1
ORDER BY 1 DESC;
这会自动从您的表中检索最小和最大天数,并在其间每天提供一行。
您可以使用 NULLIF 函数:
SELECT created, NULLIF(COUNT(id), 0)
FROM signups
GROUP BY created
ORDER BY created desc
文档:http ://www.postgresql.org/docs/8.1/static/functions-conditional.html
您应该在数据库中创建一个日历表(或在查询中生成它)并将其与您的数据库连接,然后您将获得0
空天
SELECT calendar.c_date, COUNT(signups.id)
FROM calendar
left join signups on calendar.c_date=signups.created
GROUP BY c_date
ORDER BY c_date desc
您需要使用具有一系列日期的日历表并加入它
select cal.created,coalesce(total) as total from calender_table as cal left join
(
SELECT created, COUNT(id) as total
FROM signups
GROUP BY created
) as source on cal.created=source.created
ORDER BY cal.created desc