MySQL查询以获取两个日期范围内的订单
我正在尝试执行一个查询,为每种服务类型提供两个日期范围内的订单总数MySQL查询以获取两个日期范围内的订单,mysql,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
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
只需在两个子查询上使用联接,如未经测试的:
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)
虽然不是很优雅,但pivot解决方案实际上会有类似的处理成本。为了在这两个时段中包含给定服务类型计数为零的行,您可以执行以下操作:
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
google this:pivot表应该可以工作,但最外层的SELECT需要FROM。第二个日期范围实际上返回了Rowsys我添加了From我认为这是完美的-我会在几分钟内确认并投票。谢谢注意,使用这种方法,不可能返回计数为零值的行。若在内联视图查询o1或o2的时间范围内并没有具有给定服务类型的行,则查询不会返回给定服务类型的行。我们可以使用外部连接操作来处理一端或另一端,但MySQL中不支持完全外部连接。
serviceType totalOrders_1 totalRevenue_1 totalOrders_2 totalRevenue_2
4 1 111.00 0 0.00
5 0 0.00 2 444.44