给出以下SQL查询:
SELECT orders.id, orders.shop_id,
products.price * line_items.quantity as total_value,
line_items.description, line_items.id as lineitem_id,
line_items.order_id, products.price as price,
line_items.product_id, line_items.quantity
from orders
JOIN line_items
ON line_items.order_id = orders.id
JOIN products
ON line_items.product_id = products.id;
产生以下结果:
我正在尝试使用SUM()
将同一price
的所有order_id
列加在一起,并尝试了以下新查询:
SELECT orders.id, orders.shop_id, SUM(products.price),
line_items.description, line_items.id as lineitem_id,
line_items.order_id, products.price as price,
line_items.product_id, line_items.quantity
from orders
JOIN line_items
ON line_items.order_id = orders.id
LEFT JOIN products
ON line_items.product_id = products.id
GROUP BY orders.id;
正确执行其工作(见下文)。
但是,我仍然希望保留第一张图片中所示的每一行,并将total_value
列加起来。
在第一张图片中,第一行和第二行的total_value
列(order_id
的{{1}})应为1
-这样可能吗?>
答案 0 :(得分:2)
相信您需要使用子查询来实现这一目标:
SELECT
orders.id
, orders.shop_id
, tv.total_value
, line_items.description
, line_items.id AS lineitem_id
, line_items.order_id
, products.price AS price
, line_items.product_id
, line_items.quantity
FROM orders
JOIN line_items ON line_items.order_id = orders.id
JOIN products ON line_items.product_id = products.id
JOIN (
SELECT
line_items.order_id
, SUM(products.price * line_items.quantity) total_value
FROM line_items
LEFT JOIN products ON line_items.product_id = products.id
GROUP BY
line_items.order_id
) tv ON tv.order_id = orders.id
OR
使用SUM() OVER()
(如果可用)
SELECT
orders.id
, orders.shop_id
, SUM(products.price * line_items.quantity) over(partition by orders.id) total_value
, line_items.description
, line_items.id AS lineitem_id
, line_items.order_id
, products.price AS price
, line_items.product_id
, line_items.quantity
FROM orders
JOIN line_items ON line_items.order_id = orders.id
JOIN products ON line_items.product_id = products.id