简体   繁体   中英

Sum of columns from tables in join

I have 3 tables, Orders, Orders_products and Orders_total. Currently i have a query that gets the SUM of products for each months, but now we would like to also add the freight cost that is in a different table.

I tried with the following that returned the correct total_value, but the total_shipping is 5 times as big. This i think has to due with that orders, can have multiplie products, but i cant figure out what else to do.

  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 

The returned value is:

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

Expected:

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

Here is the sqlfiddle http://sqlfiddle.com/#!2/dfe10/1/0

It contains one order, with 3 products in it. the expected total_value is 500 and the expected total_shipping is also 500, but returns 1500 (3 x products). Sadly i had to remove a lot of fields from my table due to a limit in sqlfiddle of max 8000 chars.

Try putting the shipping value into an inline view:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM