2014-11-28 3 views
1

내가 나를 주문의 총 수를 얻기 위해 각 서비스 유형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 두 번째 표현이 같은 하나의 결과를 (얻을 것입니다 : 한 기간 동안의 수익은 간단하다)

,451,515,
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 
+0

google this : 피벗 테이블 – DwB

답변

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) 

매우 우아하지,하지만 피벗 솔루션은 실제로 유사한 처리 비용있을 것입니다. 기간 중 하나의 지정된 ServiceType 자리에 대한 제로 카운트를 가지고 행을 포함하기 위해

+0

작동해야하지만 가장 바깥 쪽 'SELECT'에 대해서는 'FROM'이 필요합니다. http://sqlfiddle.com/#!2/0ca5d6/7 (실제로 행을 반환하는 두 번째 기간) –

+0

감사합니다! 나를 위해 그것을 추가 했습니까? :) – koriander

+0

예 내가 추가 했으므로 –

0

, 당신은 이런 식으로 뭔가를 할 수 :

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