简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM