我有一个带访问控制日志条目的数据库:
time : datetime (this is the access timestamp)
src: text (this is the userid)
我希望从中获取一个列表,其中显示当天有多少用户已经访问了过去7天内的天数。结果应如下所示:
number of days with access | count
1 | 30
2 | 54
3 | 123
4 | 843
5 | 3490
6 | 71
7 | 23
到目前为止我所拥有的:
以下查询返回2015-03-08中具有日志条目的用户数,该用户在2015-03-07还有一个条目。
SELECT Count(DISTINCT a.src)
FROM contacts AS a
LEFT JOIN contacts AS b
ON a.src = b.src
WHERE a.time BETWEEN Cast('2015-03-08 05:00:00' AS DATETIME) AND Cast('2015-03-09 05:00:00' AS DATETIME)
AND b.time BETWEEN Cast('2015-03-07 05:00:00' AS DATETIME) AND Cast('2015-03-08 05:00:00' AS DATETIME)
但是如上所述,我仍然坚持计算每天的天数。如果没有“只有sql”'解决方案,使用PHP进行(高效)方法也没问题。谢谢你的帮助..
答案 0 :(得分:0)
我认为你没有必要加入b表。
SELECT
DAY(a.time),
COUNT(DISTINCT a.src)
FROM contacts AS a
WHERE a.time
BETWEEN (TIMESTAMP(CURDATE()) - INTERVAL 1 WEEK)
AND TIMESTAMP(CONCAT(CURDATE(),' 23:59:59'))
GROUP BY DAY(a.time)