简体   繁体   中英

How to get the latest two dates from table for each unique id

unique_id date
A 1/1/2023
A 3/1/2023
A 5/1/2023
B 1/1/2023
B 2/1/2023
B 3/1/2023
B 4/1/2023
C 1/1/2023

I want my data to look like this

unique_id latest_date 2nd_latest_date
A 5/1/2023 3/1/2023
B 4/1/2023 3/1/2023
C 1/1/2023 Null

You could try using conditional aggregation and the row_number function as the following:

select unique_id,
       max(case when rn=1 then date end) as latest_date,
       max(case when rn=2 then date end) as _2nd_latest_date
from
(
  select *,
    row_number() over (partition by unique_id order by date desc) as rn
  from table_name
) T
group by unique_id
order by unique_id

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