In SQL, you can use the RANK()
function to assign a rank to rows within a result set, based on the values in one or more columns.
You can use the RANK()
function to find the last purchase made by a customer by ranking the purchases based on their purchase date, and then selecting the purchase with the highest rank. Here’s an example of how you can use the RANK()
function to find the last purchase made by a customer with the ID ‘1’:
WITH customer_purchases AS (
SELECT customer_id, purchase_date, RANK() OVER (PARTITION BY customer_id ORDER BY purchase_date DESC) as purchase_rank
FROM purchases
)
SELECT * FROM customer_purchases
WHERE customer_id = 1 AND purchase_rank = 1;
In this example, the RANK()
function is used to assign a rank to each purchase based on the purchase_date
column, with the most recent purchase having the highest rank. The PARTITION BY
clause is used to specify that the ranking should be done separately for each customer. Then the query selects the purchase with the rank of 1, which is the most recent purchase made by customer with the ID of 1.
It’s important to note that if there are multiple purchases with the same date, the rank function will assign the same rank to all of them.
You can also use the ROW_NUMBER()
function, which assigns a unique number to each row within a result set, based on the values in one or more columns.
WITH customer_purchases AS (
SELECT customer_id, purchase_date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date DESC) as purchase_rank
FROM purchases
)
SELECT * FROM customer_purchases
WHERE customer_id = 1 AND purchase_rank = 1;
The ROW_NUMBER()
function will always assign a unique number to each row, even if there are multiple purchases with the same date.
It’s important to note that the syntax for using the RANK and ROW_NUMBER functions may vary depending on the SQL engine you are using.
Last modified: March 3, 2023