总价格列

时间:2015-01-11 16:33:50

标签: sql

是否可以在表格中创建totalprice列,从2个不同的表中获取2个值得到答案?

e.g

orderquantity

order_id | product_code | quantity

ordertotalprice

order_id | customer_id | totalprice

产品

product_Code | product_name | product_desc | productcost

我希望totalprice列为= productcost*quantity

1 个答案:

答案 0 :(得分:0)

查询每个订单的总数:

SELECT orderquantity.order_id,
       SUM(products.productcost * orderquantity.quantity) AS total
FROM orderquantity
INNER JOIN products ON products.product_code = orderquantity.product_code
GROUP BY orderquantity.order_id

UPDATE语句中包含此查询,以更新表totalprice中的列ordertotalprice

UPDATE ordertotalprice
SET totalprice = grouped.total
FROM (
    SELECT orderquantity.order_id,
           SUM(products.productcost * orderquantity.quantity) AS total
    FROM orderquantity
    INNER JOIN products ON products.product_code = orderquantity.product_code
    GROUP BY orderquantity.order_id
) AS grouped
WHERE ordertotalprice.order_id = grouped.order_id

我假设这里表ordertotalprice已经包含了必要的记录。如果不是这样,那么您需要INSERT语句而不是UPDATE。但后来我想知道从哪里获得customer_id