我知道以下条件将返回过去7天的总数
SELECT count(id) FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
我是否可以执行一个查询,以便在过去7天内返回每个日期的7个结果数组?
例如:
day 1 - 10
day 2 - 5
day 3 - 9
..
..
..
答案 0 :(得分:3)
添加分组条款:
SELECT count(id), DATE(createdDate)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
答案 1 :(得分:3)
这将为您提供日期和计数。
SELECT DATE(createdDate),COUNT(id)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
或者,为了使结果更接近您的示例,您可以使用:
SELECT CONCAT("Day ",DATEDIFF(NOW(), createdDate)) AS day,COUNT(id)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
答案 2 :(得分:1)
select 8 - n day, count(id)
from registration
join (select 1 n union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) x
on createdDate between date_sub(curdate(), interval n day) and date_sub(curdate(), interval n-1 day)
group by day
order by day