Northwind - 十大员工名单

时间:2018-04-19 10:42:45

标签: sql sql-server

我的SQL查询还有其他问题。

我的任务是创建一个前十名员工的名单,其中1997年的销售额最高。 到目前为止,我有这个简单的查询,向我显示员工名单以及他们已售出的订单。

SELECT  
    Orders.EmployeeID,
    Orders.OrderID
FROM
    Employees
JOIN 
    Orders ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY 
    Orders.EmployeeID;

现在我想把这些数字分组,我需要知道每个员工在1997年做了多少销售。怎么做?

3 个答案:

答案 0 :(得分:2)

如果您按子查询的结果排序,则可以在不1JOIN的情况下获得所需的结果:

GROUP BY

按销售交易数量计算前十名员工。

如果你需要来自SELECT TOP 10 * FROM Employees e ORDER BY ( SELECT COUNT(*) FROM Sales s WHERE s.EmployeeId=e.EmployeeId AND DATEPART(year, o.OrderDate)=1997 ) DESC 的任何内容,比如计数,你需要走Sales路线:

GROUP BY

答案 1 :(得分:0)

WITH CTE AS 
(
SELECT EmployeeId,COUNT(*) as cn,
       DENSE_RANK(ORDER BY COUNT(*) DESC) AS rn
FROM orders
WHERE DATEPART(year,OrderDate)=1997
GROUP BY EmployeeId
) 
SELECT e.*,COALESCE(o.cn,0) AS CountOrders
FROM Employees e
LEFT JOIN CTE o
ON e.EmployeeId=o.EmployeeId
WHERE o.rn<=10

答案 2 :(得分:0)

它可以减少到这个

SELECT  top(10) EmployeeID, count(*) as cnt
FROM  Orders 
group by EmployeeID 
ORDER BY count(*) desc;