从 2 个不同的表中计算(数量*价格)的总和 [英] Calculating the SUM of (Quantity*Price) from 2 different tables

查看:52
本文介绍了从 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                62

M

推荐答案

使用:

  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.quantityp.price 为 null,则 SUM 将返回 NULL.

Mind that if either oi.quantity or p.price is null, the SUM will return NULL.

这篇关于从 2 个不同的表中计算(数量*价格)的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆