我正在尝试选择EmployeeID,FirstName
,其中emplyee的平均销售额超过平均订单数量。我计算每个员工的平均订单量和平均销售量,但由于子查询返回多个值,我无法执行比较。
平均订单量:
select SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID)
from [Order Details] od
join Orders o on o.OrderID=od.OrderID join Employees e on e.EmployeeID= o.EmployeeID
和
这是每位员工的平均销售额:
select e.FirstName, SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID) as AmountOfAverageOfSales
from [Order Details] od join Orders o on o.OrderID=od.OrderID join Employees e on e.EmployeeID= o.EmployeeID
group by e.FirstName
我希望达到EmployeeID,FirstName
,其中员工的平均销售额超过平均订单数量,但正如我在子查询(第二次查询)之前所说的那样,返回的值超过一个,因此当我使用时查询无效where
。我该如何撰写此查询?
答案 0 :(得分:0)
我很抱歉如果我浪费时间的话。我刚刚用它来解决它。
select e.FirstName
from (Orders o inner join Employees e on e.EmployeeID = o.EmployeeID inner join [Order Details] od on o.OrderID=od.OrderID) group by e.FirstName
having SUM((od.UnitPrice*od.Quantity)*(1-od.Discount))/COUNT(distinct o.OrderID) > (select SUM((od.UnitPrice*od.Quantity)*(1-od.Discount))/COUNT(distinct o.OrderID)
from [Order Details] od join Orders o on od.OrderID = o.OrderID)
答案 1 :(得分:0)
不确定您是否需要每位员工或AvgOrders的AvgOrders。如果它是前者......
select e.*, AvgOrders.AverageOrders, AvgSales.AmountOfAverageOfSales
From Employees e
inner join (select e.EmployeeID, SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID) as AverageOrders
from [Order Details] od
join Orders o on o.OrderID=od.OrderID
join Employees e on e.EmployeeID= o.EmployeeID
group by e.EmployeeID)) AvgOrders on (e.EmployeeId = AvgOrders.EmployeeId)
inner join (select e.EmployeeID, SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID) as AmountOfAverageOfSales
from [Order Details] od
join Orders o on o.OrderID=od.OrderID
join Employees e on e.EmployeeID= o.EmployeeID
group by e.EmployeeID) AvgSales on (e.EmployeeId = AvgSales.EmployeeId)
WHERE AvgSales.AmountOfAverageOfSales > AvgOrders.AverageOrders
如果是后者你可以使用......
select e.*, AvgOrders.AverageOrders, AvgSales.AmountOfAverageOfSales
From Employees e
inner join (select SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID) as AverageOrders
from [Order Details] od
join Orders o on o.OrderID=od.OrderID)) AvgOrders on (1=1)
inner join (select e.EmployeeID, SUM((od.UnitPrice*od.Quantity)*(1-Discount))/COUNT(distinct o.OrderID) as AmountOfAverageOfSales
from [Order Details] od
join Orders o on o.OrderID=od.OrderID
join Employees e on e.EmployeeID= o.EmployeeID
group by e.EmployeeID) AvgSales on (e.EmployeeId = AvgSales.EmployeeId)
WHERE AvgSales.AmountOfAverageOfSales > AvgOrders.AverageOrders