简体   繁体   English

MS SQLServer如何将两列相乘,然后将它们全部加在一起..?

[英]MS SQLServer How to multiply two columns, then add them all together..?

I'm new here. 我是新来的。 First post. 第一篇文章。 I'd really appreciate some help. 我真的很感谢您的帮助。

I'm trying to calculate total sales for all products sold. 我正在尝试计算所有已售产品的总销售额。 I have a Quantity column and a Price column. 我有一个数量列和一个价格列。 I understand how to multiply these two columns, BUT I do not know how to add them all together in the same query. 我了解如何将这两列相乘,但我不知道如何在同一查询中将它们全部加在一起。

Here is an example: Quantity: 2, 3, 1 Price: 2, 4, 5 I could do Quantity * Price to get: 4, 12, 5 But then how would I add 4 + 12 + 5 to get the total? 举个例子:数量:2,3,1价格:2,4,5我可以做数量*价格:4,12,5但是,我将如何加4 + 12 + 5来得到总数? I need this step to be included in the same query. 我需要将此步骤包含在同一查询中。

EDIT: Both the Quantity and Price columns are in the same table. 编辑:数量和价格列都在同一张表中。 SALES (Quantity, Price) 销售(数量,价格)

I am using Microsoft SQL-Server. 我正在使用Microsoft SQL-Server。

Example if you have one table: 例如,如果您有一张桌子:

SELECT dbo.orderid,
             SUM(dbo.quantity * dbo.price) AS grand_total,
        FROM ORDERITEM 

If you have two tables instead of one, then: 如果您有两个表而不是一个表,则:

 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

Adding all the rows (orderid numbers) up together to get a total, you would simply groupby and them select the sum value. 将所有行(有序号)加在一起以获得总计,您只需对它们进行分组,然后它们选择总和值。 Example below: 下面的例子:

SELECT     Orderid, SUM(quanity) AS Expr1, SUM(price) AS Expr2, SUM(quanity * price) AS Total
FROM         dbo.mytable
GROUP BY pid
HAVING      (pid = 2)

Or this in a SQL view showing the total QTY and Price: 或在显示总数量和价格的SQL视图中显示以下内容:

SELECT     Orderid, SUM(quanity) AS Quanity, SUM(price) AS Price, SUM(quanity * price) AS Total
FROM         dbo.mytable
GROUP BY pid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM