1

I have the following query which works fine when bringing out the total price of each order (thanks to the stackoverflow community):

SELECT sum((ordered_items.price + ordered_items.vat) * ordered_items.qty) + orders.postage_price + orders.postage_vat as total_price
FROM orders
JOIN ordered_items
ON orders.id_orders = ordered_items.order_id
GROUP BY orders.id_orders 

However I also want to bring out the total amount of all the orders added together. I have tried taking off the GROUP BY but this returns the wrong price. I've figured that it's adding up all the items correctly, but then only adding on one postage.

  • ordered_items - includes all the items ordered (so there can be multiple rows)
  • orders - includes the postage price of the order (there will only ever be one row per order here)

Many thanks in advance for any help.

4

1 回答 1

2

也许我遗漏了一些东西,但是,你不能把它放在一个子查询中以获得所有订单的总数:

SELECT sum(total_price) TotalAllOrders
FROM
(
  SELECT sum((ordered_items.price + ordered_items.vat) * ordered_items.qty) 
         + orders.postage_price + orders.postage_vat as total_price
  FROM orders
  JOIN ordered_items
    ON orders.id_orders = ordered_items.order_id
  GROUP BY orders.id_orders 
) src ;

您还可以使用 group by 修饰符WITH ROLLUP来获得总和和每个订单的总和:

  SELECT sum((ordered_items.price + ordered_items.vat) * ordered_items.qty) 
         + orders.postage_price + orders.postage_vat as total_price
  FROM orders
  JOIN ordered_items
    ON orders.id_orders = ordered_items.order_id
  GROUP BY orders.id_orders 
    WITH ROLLUP ;
于 2012-12-22T11:25:03.713 回答