我写了一个查询来检索我每天有多少网站注册:
SELECT created, COUNT(id)
FROM signups
GROUP BY created
ORDER BY created desc
但是,这仅检索人们实际注册的天数。如果没有人在一天内注册,我想在那一天返回0。有没有办法使用SQL来执行此操作,还是必须使用PHP解析结果?
答案 0 :(得分:3)
假设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;
这将自动从表中检索最小和最大日期,并在每天之间提供一行。
答案 1 :(得分:1)
您可以使用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
答案 2 :(得分:0)
您应该在数据库中创建一个日历表(或在查询中生成它)并与您的日历表一起加入,然后您将获得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
答案 3 :(得分:0)
您需要使用具有一系列日期并与之结合的日历表
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