本文介绍了从 2 个不同的表中计算(数量*价格)的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个表如下
PRODUCT 表
Id | Name | Price还有一个 ORDERITEM 表
Id | OrderId | ProductId | Quantity我想要做的是,计算每个产品的小计价格(数量*价格),然后将整个订单的总价值相加..
What I'm trying to do is, calculate the subtotal price for each product (Quantity*Price) then SUM the TOTAL value for the entire order..
我正在尝试这样的事情
SELECT Id, SUM(Quantity * (select Price from Product where Id = Id)) as qty FROM OrderItem o WHERE OrderId = @OrderId但这当然行不通:)
感谢任何帮助!
我只想显示整个订单的总计,所以基本上是 OrderItem 中每一行的 Quantity*Price 的总和.这是一些示例数据.
I only want to show the grand total for the entire order, so basically the sum of Quantity*Price for every row in OrderItem. Here's some sample data.
示例数据
桌子产品
Id Name Price 1 Tomatoes 20.09 4 Cucumbers 27.72 5 Oranges 21.13 6 Lemons 20.05 7 Apples 12.05表格订单项
Id OrderId ProductId Quantity 151 883 1 22 152 883 4 11 153 883 5 8 154 883 6 62M
推荐答案使用:
SELECT oi.orderid, SUM(oi.quantity * p.price) AS grand_total, FROM ORDERITEM oi JOIN PRODUCT p ON p.id = oi.productid WHERE oi.orderid = @OrderId GROUP BY oi.orderid请注意,如果 oi.quantity 或 p.price 为 null,则 SUM 将返回 NULL.
Mind that if either oi.quantity or p.price is null, the SUM will return NULL.
更多推荐
从 2 个不同的表中计算(数量*价格)的总和
发布评论