连接中表的列总和

时间:2014-01-07 08:52:52

标签: mysql

我有3个表,Orders,Orders_products和Orders_total。目前我有一个查询可以获得每月产品的总和,但现在我们还要添加不同表中的运费。

我尝试使用以下命令返回正确的total_value,但total_shipping是5倍。我认为这与订单有关,可以有多个产品,但我无法弄清楚还有什么可做。

  SELECT Count(DISTINCT O.orders_id)                AS Orders, 
       Sum(OP.final_price * OP.products_quantity) AS total_value, 
       Date_format(O.last_modified, '%m-%Y')      AS date_interval, 
       Sum(OT.value)                              AS total_shipping 
FROM   
       orders AS O 
LEFT JOIN 
        orders_total AS OT 
ON ( OT.orders_id = O.orders_id 
AND OT.class = 'ot_shipping' ), 
       orders_products AS OP 
WHERE  
       ( O.orders_id = OP.orders_id ) 
       AND ( O.orders_status = 3 ) 
GROUP  BY date_interval 
ORDER  BY O.last_modified DESC 

返回值为:

+----+------------+---------------+----------------+
| ID | total_value| date_interval | total_shipping |
+----+------------+---------------+----------------+
| 17 | 55912.2160 |    01-2014    |      24954     |

预期:

+----+------------+---------------+----------------+
| ID | total_value| date_interval | total_shipping |
+----+------------+---------------+----------------+
| 17 | 55912.2160 |    01-2014    |       4938     |

这是sqlfiddle http://sqlfiddle.com/#!2/dfe10/1/0

它包含一个订单,其中包含3个产品。预期的total_value为500,预期的total_shipping也为500,但返回1500(3个产品)。可悲的是,由于maxlfiddle对max 8000字符的限制,我不得不从我的表中删除很多字段。

1 个答案:

答案 0 :(得分:2)

尝试将运费值放入内嵌视图中:

select count(*) as Orders,
sum(ord.order_total_value) as total_value,
ord.date_interval as date_interval,
sum(ship.order_shipping_value) as total_shipping
from
(
SELECT O.orders_id,
       O.last_modified AS modified_date,
       Sum(OP.final_price * OP.products_quantity) as order_total_value, 
       Date_format(O.last_modified, '%m-%Y') as date_interval
FROM  orders AS O
      INNER JOIN orders_products AS OP on O.orders_id = OP.orders_id
WHERE O.orders_status = 3  
GROUP  BY date_interval,O.orders_id
) ord LEFT OUTER JOIN 
(
 SELECT orders_id,sum(value) as order_shipping_value
 FROM orders_total
 WHERE class='ot_shipping'
 GROUP BY orders_id
) ship ON ord.orders_id = ship.orders_id
GROUP BY ord.date_interval
ORDER BY modified_date DESC;