构造一个连接多个表并提前分组的SQL查询

时间:2017-08-03 08:11:46

标签: mysql sql

我有一个订单

  id   | order_status_id  | order_type_id  |   date
  -----------------------------------------------------
  41   |        12        |       1        | 2015-06-21
  42   |        12        |       1        | 2015-06-21
  43   |        12        |       2        | 2015-06-21
  44   |        12        |       1        | 2015-06-22
  45   |        12        |       2        | 2015-06-22
  46   |        03        |       1        | 2015-06-22
  47   |        12        |       1        | 2015-06-23
  48   |        12        |       1        | 2015-06-24
  49   |        12        |       2        | 2015-06-24
  50   |        12        |       1        | 2015-06-25

我有一个 Order_Status

  id  | order_status  | order_status_name 
  ----------------------------------------
   1  |       01      |       Draft    
   2  |       02      |     Accepted   
   3  |       03      |     Rejected    
   4  |       04      |     Processing
   -----------------------------------
   -----------------------------------
   -----------------------------------

   12 |       12      |     Completed 

我有一个 Order_Type

  id  | order_type_name 
  ---------------------
  1   | Pickup    
  2   | Delivery

我的问题:我需要为这种情况构建一个SQL查询。

       Date    | No_of_pickup_orders | No_of_delivery_orders
  ----------------------------------------------------------
    2015-06-21 |          02         |         01    
    2015-06-22 |          01         |         01    
    2015-06-23 |          01         |         00  
    2015-06-24 |          01         |         01      
    ------------------------------------------------
    ------------------------------------------------
    ------------------------------------------------

条件:此报告不应包含order_status_id = 03的记录

这是否可以在具有单个查询的SQL中实现????

到目前为止我做了什么.....

   SELECT (date AS DATE) as 'Day', count(order_type_id)
   FROM order
   WHERE created_at >= curdate() - INTERVAL DAYOFWEEK(curdate()-1)+6 DAY
   AND created_at < curdate() - INTERVAL DAYOFWEEK(curdate()-1)-1 DAY
   AND order_status_id != 3
   group by created_at;

说明:我的数据库结构比我在这里提到的要大得多。这是一个简化版本。我想要做的是从订单中获取上周的数据。这就是为什么我用这个&#34; WHERE&#34;条款和&#34; AND&#34;条款

1 个答案:

答案 0 :(得分:1)

sum()函数中,条件order_type_id=whatever返回1(真)或0(假)。而不是计算那些返回值的总和将得到你想要的结果。

   SELECT date as 'Day', sum(order_type_id=1), sum(order_type_id=2)
   FROM `order`
   WHERE true
   -- created_at >= curdate() - INTERVAL DAYOFWEEK(curdate()-1)+6 DAY
   -- AND created_at < curdate() - INTERVAL DAYOFWEEK(curdate()-1)-1 DAY
   AND order_status_id != 3
   group by date;