求和中的乘法

时间:2017-08-04 20:27:55

标签: sql sql-server ssms

我正在编写存储过程。存储过程将获取所有库存条目的库存,并返回该产品的所有单元的总成本。我按产品和供应商信息进行分组,然后就数量和价值而言,我有这个

SELECT i.SupplierID, i.SupplierName, p.ProductID, p.ProductName,  
       SUM(i.Quantity) AS Quantity, 
       SUM(i.Quantity * i.UnitCost) AS TotalValue, 
       SUM(i.Quantity * i.UnitCost) OVER() AS AllProductsTotal
FROM Inventory i
JOIN Products p on p.ProductID = i.ProductID
GROUP BY i.SupplierID, i.SupplierName, p.ProductID, p.ProductName

然而,当我尝试运行create ...

  

Msg 8120,Level 16,State 1,Line 2

     

专栏' Inventory.Quantity'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

     

Msg 8120,Level 16,State 1,Line 2

     

专栏' Inventory.UnitCost'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

列是聚合的,只有在聚合中,它们只是在同一个聚合中。我做错了什么?

2 个答案:

答案 0 :(得分:1)

如果我做对了,你想将窗口函数应用于聚合

SELECT i.SupplierID, i.SupplierName, p.ProductID, p.ProductName,  
       SUM(i.Quantity) AS Quantity, 
       SUM(i.Quantity * i.UnitCost) AS TotalValue, 
       SUM(SUM(i.Quantity * i.UnitCost)) OVER() AS AllProductsTotal
FROM Inventory i
JOIN Products p on p.ProductID = ie.ProductID
GROUP BY i.SupplierID, i.SupplierName, p.ProductID, p.ProductName

答案 1 :(得分:0)

您可以按以下方式更改代码


Select *, Sum(TotalValue) as AllProductsTotal over() 
from (
   SELECT i.SupplierID, i.SupplierName, p.ProductID, p.ProductName,  
       SUM(i.Quantity) AS Quantity, 
       SUM(i.Quantity * i.UnitCost) AS TotalValue--, 
       --SUM(i.Quantity * i.UnitCost) OVER() AS AllProductsTotal
   FROM Inventory i
   JOIN Products p on p.ProductID = ie.ProductID
   GROUP BY i.SupplierID, i.SupplierName, p.ProductID, p.ProductName
) a