MySQL查询以获取两个日期范围内的订单

时间:2014-11-28 20:58:29

标签: mysql

我正在尝试执行单个查询,以便为每种服务类型的两个日期范围提供订单总计

orderDate   serviceType revenue
2014-01-01  1           3.00
2014-01-02  2           4.00
2014-01-01  1           5.00
2014-01-03  3           3.00
2014-01-02  1           4.00
2014-01-04  2           5.00
2014-01-20  1           4.00
2014-01-21  2           5.00
2014-01-23  1           6.00
2014-01-24  3           4.00
2014-01-20  1           5.00
2014-01-21  2           6.00

获取一个日期范围的订单总数和收入的查询很简单:

select serviceType, count(*) as totalOrders, sum(revenue) as totalRevenue
from   orders 
where  orderDate >= '2014-01-01' 
   and orderDate <= '2014-01-05'
group by serviceType

但是我想在一个查询中执行两个日期范围,并获得一个这样的结果(其中totalOrders_1和totalRevenue_1代表第一个日期范围,totalOrders_2和totalRevenue_2代表第二个日期范围)

serviceType totalOrders_1   totalRevenue_1      totalOrders_2   totalRevenue_2
1           3               12.00               3               15.00
2           2               9.00                2               11.00
3           1               3.00                1               4.00

2 个答案:

答案 0 :(得分:2)

只需对两个子查询使用连接,例如(未经测试):

select o1.serviceType, totalOrders_1, totalRevenue_1, totalOrders_2, totalRevenue_2
from
(select serviceType, count(*) as totalOrders_1, sum(revenue) as totalRevenue_1
from   orders 
where  orderDate >= '2014-01-01' 
   and orderDate <= '2014-01-05'
group by serviceType) o1
inner join
(select serviceType, count(*) as totalOrders_2, sum(revenue) as totalRevenue_2
from   orders 
where  orderDate >= '2014-02-01' 
   and orderDate <= '2014-02-05'
group by serviceType) o2 using (serviceType)

不是很优雅,但是透视解决方案实际上会有类似的处理成本。

答案 1 :(得分:0)

为了包含任一期间给定serviceType的计数为零的行,您可以执行以下操作:

SELECT o.serviceType
     , SUM(IF(o.orderDate >= '2014-01-01' AND o.orderDate <= '2014-01-05'
             ,1,0)
       ) AS totalOrders_1
     , SUM(IF(o.orderDate >= '2014-01-01' AND o.orderDate <= '2014-01-05'
             ,o.revenue,0)
       ) AS totalRevenue_1
     , SUM(IF(o.orderDate >= '2014-02-01' AND o.orderDate <= '2014-02-05'
             ,1,0)
       ) AS totalOrders_2
     , SUM(IF(o.orderDate >= '2014-02-01' AND o.orderDate <= '2014-02-05'
             ,o.revenue,0)
       ) AS totalRevenue_2
  FROM orders o
 WHERE (o.orderDate >= '2014-01-01' AND o.orderDate <= '2014-01-05')
    OR (o.orderDate <= '2014-02-01' AND o.orderDate <= '2014-02-05')
 GROUP BY o.serviceType

这种方法可以返回如下行:

serviceType totalOrders_1 totalRevenue_1 totalOrders_2   totalRevenue_2
4           1             111.00         0               0.00
5           0             0.00           2               444.44