从 2 个不同的表中计算(数量*价格)的总和

编程入门 行业动态 更新时间:2024-10-15 04:20:17
本文介绍了从 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.quantity 或 p.price 为 null,则 SUM 将返回 NULL.

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

更多推荐

从 2 个不同的表中计算(数量*价格)的总和

本文发布于:2023-11-21 23:39:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   数量   价格

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!