2013-04-11 51 views
3

我知道下面的情況將在過去7天單查詢來獲取的過去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 
.. 
.. 
.. 

回答

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) 
+0

哇這就是偉大的,你估計它的可能的,如果顯示爲0計數有沒有在某一天的登記? 天1 - 4 每天2 - 3 天3 - 0 天4 - 1 天5 - 0 類似的東西 – vinz 2013-04-12 08:23:11

+0

我不知道是否有以顯示與不註冊一個0的方式以上查詢。您可以在PHP端執行該操作,或者使用@ Barmar的答案。 – Jim 2013-04-15 03:43:05

3

添加組by語句:

SELECT count(id), DATE(createdDate) 
FROM registration 
WHERE createdDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() 
GROUP BY DATE(createdDate) 
+0

+1簡單,最好的 – alwaysLearn 2013-04-11 04:07:22

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 
相關問題