Skip to content
Advertisement

MYSQL: Get second last record for every customer from a table

my table looks like this

ID  DATE      customer_id
 1   2020-10-01   10
 2   2020-10-01   11
 3   2020-10-02   10
 4   2020-10-03   10
 5   2020-10-03   11

What i am trying to fetch from the list based on second last ID for each customer

ID  DATE      customer_id
 2   2020-10-01   11
 3   2020-10-02   10

Advertisement

Answer

Using ROW_NUMBER is suitable here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY DATE DESC) rn
    FROM yourTable
)

SELECT ID, DATE, customer_id
FROM cte
WHERE rn = 2;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement