Welcome Back

Google icon Sign in with Google
OR
I agree to abide by Pharmadaily Terms of Service and its Privacy Policy

Create Account

Google icon Sign up with Google
OR
By signing up, you agree to our Terms of Service and Privacy Policy
Instagram
youtube
Facebook

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: