我试图通过当前一周的列表(过去7天)获取所有用户的COUNT
此查询有效但如果该日期不存在则不返回0:
SELECT COUNT(*) AS attempt_count,
DATE_FORMAT(attempt_date,'%Y/%m/%d') AS attempt_date
FROM users_attempts
WHERE DATE_SUB(attempt_date, INTERVAL 1 DAY) > DATE_SUB(DATE(NOW()), INTERVAL 1 WEEK)
GROUP BY DAY(attempt_date) DESC;
此查询返回每天上一个当前周的所有尝试的COUNT,我得到了这个(我只有1条记录):
attempt_count | attempt_date
1 2014/06/19
我想要这个结果:
attempt_count | attempt_date
1 2014/06/19
0 2014/06/18
0 2014/06/17
0 2014/06/16
0 2014/06/15
0 2014/06/14
0 2014/06/13
非常感谢
答案 0 :(得分:2)
从我之前的帖子MySql Single Table, Select last 7 days and include empty rows
回答这里有什么可以让日期选择动态
select
t1.attempt_date,
coalesce(SUM(t1.attempt_count+t2.attempt_count), 0) AS attempt_count
from
(
select DATE_FORMAT(a.Date,'%Y/%m/%d') as attempt_date,
'0' as attempt_count
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
)t1
left join
(
SELECT DATE_FORMAT(attempt_date,'%Y/%m/%d') AS attempt_date,
COUNT(*) AS attempt_count
FROM users_attempts
WHERE DATE_SUB(attempt_date, INTERVAL 1 DAY) > DATE_SUB(DATE(NOW()), INTERVAL 1 WEEK)
GROUP BY DAY(attempt_date) DESC
)t2
on t2.attempt_date = t1.attempt_date
group by DAY(t1.attempt_date)
order by t1.attempt_date desc;
<强> DEMO 强>
答案 1 :(得分:0)
创建日历表,或者您可以尝试:
SELECT COUNT(*) AS attempt_count,
DATE_FORMAT(ca_date,'%Y/%m/%d') AS attempt_date
FROM
(SELECT STR_TO_DATE('2014/06/19', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/18', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/17', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/16', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/15', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/14', '%Y/%m/%d') ca_date
UNION ALL SELECT STR_TO_DATE('2014/06/13', '%Y/%m/%d') ca_date) AS calendar
LEFT JOIN users_attempts ON users_attempts.attempt_date = calendar.ca_date
GROUP BY calendar.ca_date
ORDER BY calendar.ca_date DESC;