简体   繁体   English

每天记录计数,包括 0 个值

[英]Records count per day, including 0 values

I'm trying to get a query that will show number of visits per day for the last 7 days.我正在尝试获取一个查询,该查询将显示过去 7 天每天的访问次数。 Query that I come up with works but it has limitation I do not know how to get rid of.我提出的查询有效,但它有我不知道如何摆脱的限制。

Imagine, it is August 4th, 2019. Our table visits keeps timestamps of users visits to a website:想象一下,现在是 2019 年 8 月 4 日。我们的visits表保留了用户访问网站的时间戳:

ID | timestamp
1 | 2019-08-03
2 | 2019-08-03
3 | 2019-08-02
4 | 2019-07-31
5 | 2019-07-31
6 | 2019-07-31
7 | 2019-07-31
8 | 2019-07-30
9 | 2019-07-30
10 | 2019-07-28

Objective: get number of visits to a website per day for the last 7 days.目标:获取过去 7 天内每天访问网站的次数。 So the result should be something like:所以结果应该是这样的:

DATE | NumberOfVisitis
2018-08-04 | 0
2018-08-03 | 2
2018-08-02 | 1
2018-08-01 | 0
2018-07-31 | 4
2018-07-30 | 1
2018-07-29 | 0

My query includes only dates registered in DB (it excludes days with no visits).我的查询仅包括在 DB 中注册的日期(不包括没有访问的天数)。 This makes sense as query is data dependent, instead of calendar.这是有道理的,因为查询依赖于数据,而不是日历。

SELECT DATE_FORMAT(`timestamp`, "%Y%m/%d") AS Date, COUNT(`id`) AS
NumberOfVisitis FROM `visits` WHERE `timestamp` >= DATE_ADD(NOW(),
INTERVAL -7 DAY) GROUP BY DAY(`timestamp`) ORDER BY `timestamp` DESC

Can you please let me know how can I modify my query to include days with no visits in the query result?您能否让我知道如何修改我的查询以在查询结果中包含没有访问的天数?

MySQL lacks anything like Postgres's generate_series so we have to fake it. MySQL缺少像Postgres的generate_series这样的东西,所以我们不得不假装它。

Simplest thing to do is to make a table with a bunch of numbers in it. 最简单的方法是制作一个包含大量数字的表格。 This will be useful for generating lots of things. 这对于生成很多东西很有用。

create table numbers ( number serial );
insert into numbers () values (), (), (), (), (), (), ();

From that we can generate a list of the last 7 days. 由此我们可以生成过去7天的列表。

select date_sub(date(now()), interval number-1 day) as date
from numbers
order by number
limit 7

Then using that as a CTE (or a subquery) we left join it with visits. 然后使用它作为CTE(或子查询)我们left join它与访问。 A left join means all dates will be present. 左连接表示将出现所有日期。

with dates as (
    select date_sub(date(now()), interval number-1 day) as date
    from numbers
    order by number
    limit 7
)
select date, coalesce(sum(id), 0)
from dates
left join visits on date = timestamp
group by date
order by date

@Schwern, finally I was able to find a solution, based on your tip. @Schwern,最后我能够根据你的提示找到解决方案。 As CTE is not available on my server, I created a view, and here is the result: https://ibb.co/zxRcwN3 由于CTE在我的服务器上不可用,我创建了一个视图,结果如下: https//ibb.co/zxRcwN3

MANY THANKS! 非常感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM