我遇到以下问题的问题:
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
我们的想法是带回订单的总价,包括邮资。
我遇到的问题是,如果订单在'ordered_items'中包含多个商品,则上述总和会多次计算'订单'中的邮资。
如何重写此查询以便邮资只计算一次?
非常感谢您的任何帮助。
答案 0 :(得分:2)
您不需要子查询,只需将postage_price和vat移出聚合和GROUP BY:
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.postage_price, orders.postage_vat
答案 1 :(得分:1)
您需要添加分组
GROUP BY ordered_items.order_id
答案 2 :(得分:0)
SELECT items.total + orders.postage_price + orders.postage_vat) AS total_price
FROM orders
JOIN (SELECT order_id, SUM((ordered_items.price + ordered_items.vat) * ordered_items.qty) AS total
FROM ordered_items
GROUP BY order_id) items
ON orders.id_orders = items.order_id