从多个表中选择聚合

时间:2017-02-09 01:41:24

标签: sql group-by aggregate dml

我有两个表:Orders Table

OrderDetail

我想在每个订单中选择总项目金额,由UnitPrice计算*数量,总折扣=总和(((数量*单位价格)/ 100)*折扣* 100)和AverageFreight =(运费/总项目在订单)*订单总项目

我写这样的select语句:

select  Orders.OrderID,CustomerID, EmployeeID, ProductID,ShippedDate, RequiredDate, ShipVia,(Freight/sum(Quantity))*Quantity 'TotalFreight', 
Quantity * UnitPrice 'LineItemTotal',sum(Quantity) 'Line Item Quantity',sum(((Quantity * UnitPrice)/100) * Discount*100) 'Total Line Discount',Discount  from Orders
inner join [Order Details] on Orders.OrderID = [Order Details].OrderID
group by Orders.OrderID,Orders.CustomerID, Orders.EmployeeID, [Order Details].ProductID, Orders.RequiredDate, Orders.ShipVia, Orders.Freight, [Order Details].Quantity,[Order Details].UnitPrice, [Order Details].Discount, Orders.ShippedDate

但是,它不会计算AverageFreight权限。我究竟做错了什么? enter image description here

1 个答案:

答案 0 :(得分:2)

您不需要聚合。窗函数应该足够了:

select o.*, od.*, 
       (Freight / order_quantity)*Quantity as AllocatedFreight, 
       Quantity * UnitPrice as LineItemTotal,
       Quantity as [Line Item Quantity],
       (((Quantity * UnitPrice)/100) * Discount*100) as [Total Line Discount,
       Discount 
from Orders o inner join
     (select od.*, sum(quantity) over (partition by od.orderId) as order_quantity
      from [Order Details] od
     ) od
     on o.OrderID = od.OrderID;