我有这些表格:
如何显示销售数量最多的员工的姓氏和名字?
我知道我必须使用多个连接,别名和一些HAVING语句,但我不确定如何继续。
答案 0 :(得分:0)
根本不需要HAVING
。如您所建议的那样,加入连接键上的所有表,然后按两个员工名称列进行分组。
以下查询(带派生表)应该与任何RDBMS无关,但排除了将结果限制为仅一行的最终考虑因素,这取决于RDBMS
SELECT d.FirstName, d.LastName, d.TotalQuantity
FROM
(
SELECT e.FirstName, e.LastName, SUM(od.Quantity) AS TotalQuantity
FROM OrderDetails od
INNER JOIN Orders o ON OrderDetails.OrderId = o.OrderId
INNER JOIN Customers c ON o.CustomerName = c.CustomerName -- Switch to a surrogate key
INNER JOIN Employees e ON c.EmployeeId = e.EmployeeId
-- WHERE od.ProductId = `FooBars` -- If you need a filter
GROUP BY e.FirstName, e.LastName
) d
ORDER BY d.TotalQuantity DESC;
对于“只是最高员工”的要求,您需要将行数限制为1,这取决于RDBMS:
ORDER BY ... LIMIT 1;
for MySql ORDER BY ... FETCH FIRST 1 ROWS ONLY;
以获取较新版本的SqlServer和Oracle SELECT top 1 d.FirstName, ..
注意:
ServingEmployeeCustomer
联结表按顺序发出声音。答案 1 :(得分:0)
试试这个:
SELECT e.FirstName, e.LastName, SUM(od.Quantity) AS Quantity
FROM OrderDetails od
INNER JOIN Orders o ON od.OrderId = o.OrderId
INNER JOIN Customers c ON o.CustomerName = c.CustomerName
INNER JOIN Employees e ON c.EmployeeId = e.EmployeeId
GROUP BY e.FirstName, e.LastName
ORDER BY Quantity DESC;