首页 > 解决方案 > 左连接并对每一行求和

问题描述

我有一个名为 orders(orderID、customerID、purchaseDate 和 paymentType)和 orderLine(orderID、upc、productName、quantity、price)的表。我正在尝试加入这两个表,以便它主要显示订单表,然后在最右侧为每个订单提供一个总价格列。这是我到目前为止所拥有的,但它将每一行的总数加到一个中。我希望每个单独的行都有自己的总和,方法是根据 orderID 乘以数量*价格。

SELECT orders.orderID, SUM(orderLine.price * orderLine.quantity) 
FROM orderLine 
LEFT JOIN orders 
ON orders.orderID = orderLine.orderID

标签: sqljoinsum

解决方案


您需要添加 group by 子句

SELECT orders.orderID, SUM(orderLine.price * orderLine.quantity) 
FROM orderLine 
LEFT JOIN orders 
ON orders.orderID = orderLine.orderID
grou by orders.orderID

推荐阅读