我正在尝试使用以下查询获取每张发票的总金额,但我收到以下错误:
Msg 4109,Level 15,State 1,Line 3 窗口函数不能在另一个窗口函数或聚合的上下文中使用。
查询
SELECT
SP.InvoiceNo,
Sum(CAST((SPD.Quantity * SPD.UnitPrice) / (SUM(SPD.Quantity * SPD.UnitPrice) OVER ()) * Sp.Shipping_Cost + (SPD.Quantity * SPD.UnitPrice) / (SUM(SPD.Quantity * SPD.UnitPrice) OVER ()) * Sp.Customs_Cost + SPD.Quantity * SPD.UnitPrice - (SPD.Discount / 100) * SPD.Quantity * SPD.UnitPrice AS decimal(10, 2))) AS [Total Amount]
FROM dbo.Stock_Purchase SP
INNER JOIN dbo.Stock_Purchase_Details SPD
ON SP.Purchase_ID = SPD.Purchase_ID
INNER JOIN dbo.Store S
ON SPD.Pro_ID = S.Pro_ID
group by SP.InvoiceNo,SPD.Quantity,SPD.UnitPrice
答案 0 :(得分:2)
如错误消息中所述,您无法在sum()over()
聚合内使用sum
聚合窗口函数。
尝试使用派生表
SELECT InvoiceNo,
Sum(Cast(( sales ) / ( total_sales ) * Shipping_Cost + ( sales ) / ( total_sales ) * Customs_Cost + sales - ( Discount / 100 ) * sales AS DECIMAL(10, 2))) AS [Total Amount]
FROM (SELECT SP.InvoiceNo,
Sp.Shipping_Cost,
Sp.Customs_Cost,
SPD.Quantity,
SPD.UnitPrice,
Sum(SPD.Quantity * SPD.UnitPrice)
OVER() AS total_sales,
SPD.Discount,
SPD.Quantity * SPD.UnitPrice AS sales
FROM dbo.Stock_Purchase SP
INNER JOIN dbo.Stock_Purchase_Details SPD
ON SP.Purchase_ID = SPD.Purchase_ID
INNER JOIN dbo.Store S
ON SPD.Pro_ID = S.Pro_ID) a
GROUP BY InvoiceNo,
Quantity,
UnitPrice
我想通过添加样本数据和预期结果可以改进查询
答案 1 :(得分:0)
我相信你想要这样的东西:
SELECT SP.InvoiceNo,
SUM(SPD.Quantity * SPD.UnitPrice * (1 - SP.Discount)) + sp.Shipping_Cost as Total_amount
FROM dbo.Stock_Purchase SP INNER JOIN
dbo.Stock_Purchase_Details SPD
ON SP.Purchase_ID = SPD.Purchase_ID INNER JOIN
dbo.Store S
ON SPD.Pro_ID = S.Pro_ID
GROUP BY SP.InvoiceNo, sp.Shipping_Cost;
注意:
GROUP BY
列太多了。