Instagram
youtube
Facebook
Twitter

Use RANK() to Get the Top 3 Employees by Order Count

Use RANK() to Get the Top 3 Employees by Order Count

Order Table:


Query Explanation:

  • COUNT(OrderID) counts the number of orders handled by each employee.

  • RANK() assigns a rank to employees based on total orders, from highest to lowest.

  • RANK() allows ties—if two employees have the same count, they'll share the same rank.

  • The outer query filters only the top 3 ranked employees (rk <= 3), which may return more than 3 rows if there's a tie.


SQL Query:

SELECT *
FROM (
    SELECT 
        EmployeeID,
        COUNT(OrderID) AS TotalOrders,
        RANK() OVER (ORDER BY COUNT(OrderID) DESC) AS rk
    FROM Orders
    GROUP BY EmployeeID
) AS RankedEmployees
WHERE rk <= 3;


Output: