SUM()每个具有相同ID的行

时间:2018-09-14 03:04:04

标签: sql sqlite

给出以下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;

产生以下结果:

sql query result

我正在尝试使用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;

正确执行其工作(见下文)。

sql query result with SUM

但是,我仍然希望保留第一张图片中所示的每一行,并将total_value列加起来。

在第一张图片中,第一行和第二行的total_value列(order_id的{​​{1}})应为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