我有以下查询在提出每个订单的总价时工作正常(感谢stackoverflow社区):
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
但是我还要提出一起加入的所有订单的总金额。我试过取消GROUP BY,但这会返回错误的价格。我认为它正确地添加了所有项目,但之后只添加了一个邮资。
非常感谢您的任何帮助。
答案 0 :(得分: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 ;
您还可以使用修改器 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 ;