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 ROW_NUMBER to Get the Latest Order per Customer

Use ROW_NUMBER to Get the Latest Order per Customer


Order Table:


Query Explanation:

  • ROW_NUMBER() OVER (...) assigns a unique row number to each order per customer, based on latest OrderDate first (DESC).

  • PARTITION BY CustomerID groups the rows by each customer so that numbering resets for each one.

  • ORDER BY OrderDate DESC ensures the latest order gets ROW_NUMBER = 1.

  • The outer query filters WHERE rn = 1, which means only the latest order of each customer is selected.


SQL Query:

SELECT *
FROM (
    SELECT 
        OrderID,
        CustomerID,
        OrderDate,
        ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) AS rn
    FROM Orders
) AS RankedOrders
WHERE rn = 1;


Output: