2
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

上面的查询是从表中获取的,这意味着从当前日期(假设 2013-09-13)开始的前 7 天,基于 group by createdate。结果显示 3 行。在获取时间时,我只想在上面的 RESULT 中添加日期和计数(不在 DB 中)虚拟日期,如下所示。请帮助......如何为此编写查询......

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

4

1 回答 1

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 中动态地执行此操作并不容易,除非您在某处有一个numbersor表。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 );
于 2013-09-13T11:15:04.557 回答