Select 从多个表中汇总
Select aggregate from multiple tables
我有 2 个表,它们是:
和
我想 select 每个订单中的总项目行金额,由单价*数量、总折扣 = sum(((数量 * 单价)/100) * 折扣*100) 和平均运费 = (Freight/Total 订单项)* 总订单项
我这样写 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。我究竟做错了什么?
您不需要对此进行汇总。 window 函数应该足够了:
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;
我有 2 个表,它们是:
和
我想 select 每个订单中的总项目行金额,由单价*数量、总折扣 = sum(((数量 * 单价)/100) * 折扣*100) 和平均运费 = (Freight/Total 订单项)* 总订单项
我这样写 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。我究竟做错了什么?
您不需要对此进行汇总。 window 函数应该足够了:
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;