Search code examples
sqlgroup-byaggregatedml

Select aggregate from multiple tables


I have 2 tables which are:Orders Table

and OrderDetail

I want to select Total Item Line Amount in each Order which is calculated by UnitPrice*Quantity, Total Discount = sum(((Quantity * UnitPrice)/100) * Discount*100) and AverageFreight = (Freight/Total Item In Order) * Total Line Item In Order

I write select statement like this:

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

However, it does not calculate the AverageFreight right. What am I doing wrong? enter image description here


Solution

  • You don't need aggregation for this. A window function should suffice:

    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;