Skip to content
Advertisement

Parsing out inconsistent data to grab specific year

I have a TableA with a column Years. Each row value in this column is formatted as a mix of:

2021;2017;2019;2022

and

2021,2017,2019

The number of years listed in each row varies (could be 1, could be 10).

I have a task to pull the latest year for each row. I am not even sure where to start on this, so I haven’t tried anything as of yet.

Any ideas?

Advertisement

Answer

Use unnest(string_to_array(...)) to convert the values to rows, then take the max of the expanded column:

select ID, max(year) as max_year
from (select id, unnest(string_to_array(Years, ';')) as year from TableA) x
group by ID

See live demo.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement