我确实知道以下条件将返回过去 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
..
..
..
添加 group-by 子句:
SELECT count(id), DATE(createdDate)
FROM registration
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
GROUP BY DATE(createdDate)
这将为您提供日期和计数。
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)
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