SELECT TOP 1 e.EmployeeID
FROM Employees e
INNER JOIN Orders o ON o.EMployeeID = e.EmployeeID
INNER JOIN (
SELECT OrderID,
SUM((UnitPrice * Quantity) - Discount) AS TotalOrderPrice
FROM [Order Details]
GROUP BY OrderID
) oi ON oi.OrderID = o.OrderID
GROUP BY e.employeeid
ORDER BY TotalOrderPrice * 0.1 DESC,
COUNT(o.OrderID) ASC
Msg 8127, Level 16, State 1, Line 11
Column "oi.TotalOrderPrice" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
最佳答案
如果您使用GROUP BY
,则只能SELECT
(因此,ORDER
)列,这些列是
- 您分组的任一列
- 可以是聚合函数(例如
MAX()
或COUNT()
)
MySQL 没有这个限制,但它只是 SQL 标准的 MySQL 特定扩展。任何其他 SQL 服务器(包括 Microsoft SQL)都具有此功能。
关于SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287125/