MYSQL SELECT QUERY显示之间的所有日期,即使count = 0时不存在数据

时间:2015-04-24 10:24:56

标签: mysql database

  

以下是查询我已写入获取订单计数,状态= 1,上周

  SELECT count(*) as order_count,
         DATE_FORMAT(order_date,'%d-%b-%Y') as order_date,
         status 
    FROM customer_order 
   WHERE date(order_date) >= curdate() 
                              - INTERVAL DAYOFWEEK(curdate())+6 DAY
     AND date(order_date) < curdate() 
                              - INTERVAL DAYOFWEEK(curdate())-1 DAY 
     AND status=1
GROUP BY DATE_FORMAT(order_date, '%Y%m%d'),
         status
  

我的结果仅针对表格中的日期。如果特定日期数据不存在,我需要 count = 0 的所有日期。

1 个答案:

答案 0 :(得分:0)

你可以尝试:

SELECT DATE_FORMAT(c1.order_date,'%d-%b-%Y') AS order_date
  FROM customer_order AS c1
 WHERE DATE_FORMAT(c1.order_date,'%d-%b-%Y') 
                  IN ( SELECT DATE_FORMAT(c2.order_date,'%d-%b-%Y') as order_date2
                         FROM customer_order AS c2
                        WHERE date(DATE_FORMAT(c2.order_date,'%d-%b-%Y')) >= curdate() 
                                - INTERVAL DAYOFWEEK(curdate())+6 DAY
                          AND date(DATE_FORMAT(c2.order_date,'%d-%b-%Y')) < curdate() 
                                - INTERVAL DAYOFWEEK(curdate())-1 DAY 
                          AND c2.status=1
                     GROUP BY DATE_FORMAT(DATE_FORMAT(c2.order_date,'%d-%b-%Y'), '%Y%m%d'),
                              c2.status
                       HAVING count(*)=0
                     )