SELECT COUNT(*),Date(createDate) FROM EEC_Order WHERE createDate
BETWEEN DATE_SUB(CURDATE(),INTERVAL 7 DAY ) AND CURDATE()
group by Date(createDate) ;
COUNT(*) Date(createDate)
3 2013-09-08
1 2013-09-11
2 2013-09-12
以上查询是从表中获取的,表示从当前日期开始的前7天(假设2013-09-13),基于创建的组。结果显示3行。在获取时间的同时,我想在上面的RESULT中添加日期和计数(不在数据库中)虚拟日期,这些日期并不像下面那样。请帮忙......如何写这个查询...
COUNT(*) Date(createDate)
0 2013-09-06
0 2013-09-07
3 2013-09-08
0 2013-09-09
0 2013-09-10
1 2013-09-11
2 2013-09-12
问候
sakir
esquareinfo
答案 0 :(得分:3)
您需要一个日期列表和一个左外连接。以下是制定查询的一种方法:
SELECT COUNT(o.createDate), dates.thedate
FROM (select DATE_SUB(CURDATE(), INTERVAL 7 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 6 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 5 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 4 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 3 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 2 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 1 DAY ) as thedate union all
select DATE_SUB(CURDATE(), INTERVAL 0 DAY ) as thedate
) dates left outer join
EEC_Order o
on Date(createDate) = dates.thedate
group by dates.thedate ;
编辑:
在MySQL中动态执行此操作并不容易,除非您在某处有numbers
或dates
表。以下采用这种方法,首先创建一个包含1000个数字的列表(带有where
子句),然后进行连接和聚合:
select DATE_SUB(CURDATE(), INTERVAL n.n DAY ), count(e.CreateDate)
from (select (n1*100 + n2*10 + n3) as n
from (select 0 as n 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
) n1 cross join
(select 0 as n 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
) n2 cross join
(select 0 as n 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
) n3
where (n1*100 + n2*10 + n3) <= 30
) n left outer join
EEC_Order o
on Date(createDate) = DATE_SUB(CURDATE(), INTERVAL n.n DAY )
group by DATE_SUB(CURDATE(), INTERVAL n.n DAY );