如何同时选择两个选择总和

时间:2014-03-19 01:11:32

标签: sql

我正在尝试使用该公式

像这样

sum((freight/sum(Quantity))*Quantity) for lineitemfright

我试过的代码并没有总结我想要的一个值

select sum(
     (
        Northwind.dbo.orders.Freight 
        /
        (
            select SUM(
                Northwind.dbo.[Order Details].Quantity
            )
            from Northwind.dbo.[Order Details] 
            where Northwind.dbo.[Order Details].OrderID = Northwind.dbo.orders.OrderID
        )
        *
        Northwind.dbo.[Order Details].Quantity
    )
) as LineItemFreight 
from Northwind.dbo.[Order Details] 
inner join Northwind.dbo.Orders 
on Northwind.dbo.[Order Details].OrderID= northwind.dbo.Orders.OrderID
where Northwind.dbo.orders.ShippedDate is not null

然而它一直在说错误。

Msg 130, Level 15, State 1, Line 5
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
 sum((freight/sum(Quantity))*Quantity)

我试图在不使用分组的情况下将一个值相加。

1 个答案:

答案 0 :(得分:0)

使用变量并执行

  @DECLARE @tEMPSUM bigint

    SET @TEMPSUM=select SUM(Northwind.dbo.[Order Details].Quantity)from Northwind.dbo.[Order Details] 
            where Northwind.dbo.[Order Details].OrderID = Northwind.dbo.orders.OrderID

然后

select sum((Northwind.dbo.orders.Freight / @tEMPSUM)*Northwind.dbo.[Order Details].Quantity) as LineItemFreight 
from Northwind.dbo.[Order Details] 
inner join Northwind.dbo.Orders 
on Northwind.dbo.[Order Details].OrderID= northwind.dbo.Orders.OrderID
where Northwind.dbo.orders.ShippedDate is not null