我有一个包含三列的数据库表visitors
:
id | Name | checkin_date |
1 | Reg | 2018-04-20T08:28:54.446Z |
2 | Meg | 2018-04-21T08:28:54.446Z |
3 | Ted | 2018-04-21T08:28:54.446Z |
4 | Bin | 2018-04-23T08:28:54.446Z |
有一些这样的记录。 我只想获取过去7天每天的记录数。现在,我能够使用:
来获取所有日期的每天访客数select count(id) as no_of_users
, DATE_FORMAT(checkin_date, '%d %b, %Y') as date
from visitors
GROUP
BY DATE(checkin_date)
但是,这将显示所有记录每天的用户数。如何获取仅过去7天的记录。
答案 0 :(得分:2)
select count(id) as no_of_users, DATE_FORMAT(checkin_date, '%d %b, %Y') as date from visitors
where checkin_date >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY DATE(checkin_date)
您要在哪里进行日期字段> =最近7天
答案 1 :(得分:2)
根据您的问题。
您需要创建一个日历表,然后在日历表上创建LEFT JOIN
。
SELECT DATE(t.dt),count(t1.id) cnt
FROM
(
SELECT NOW() dt
UNION ALL
SELECT NOW() - INTERVAL 1 DAY
UNION ALL
SELECT NOW() - INTERVAL 2 DAY
UNION ALL
SELECT NOW() - INTERVAL 3 DAY
UNION ALL
SELECT NOW() - INTERVAL 4 DAY
UNION ALL
SELECT NOW() - INTERVAL 5 DAY
UNION ALL
SELECT NOW() - INTERVAL 6 DAY
UNION ALL
SELECT NOW() - INTERVAL 7 DAY
) t LEFT JOIN T t1
ON DATE(t.dt) = DATE(t1.checkin_date)
group by t1.name,DATE(t.dt)
sqlfiddle:http://sqlfiddle.com/#!9/59f49b/5
答案 2 :(得分:1)
select id, count(id) as TOTAL, min (checkin_date) as no_of_users
from visitors
where checkin_date between '<Start Date>' and '<End Date>'
GROUP
BY Id,checkin_date