Skip to content
Advertisement

LEFT JOIN by closer value condition

I have this query

In the second LEFT JOIN, I would like to change the second condition pob.year = proc.anno_eleccion so that it does not only search for the exact year when joining. Instead, I would like to get the closer year stored in my pob table. For example, the first year stored in pob is 2003, so I want all the entries in loc whose year is lower than 2003 to be matched with that value when performing the join. Also at the inverse, the last year stored in pob is 2020, so I want those entries in loc whose year is 2021 (or even greater), to be matched with the 2020 row from my pob table. When the exact year is contained in pob table, it should be used for the join.

Advertisement

Answer

1. If you want the nearest year to NOW

I don’t think of a direct join but you can try this one by using ROW_NUMBER() function to sort data by year and pick the first result to join: (WHERE rn = 1 picks the first index, so it prevents any duplicate)

2. If you want the nearest year to your data

Even it’s not best practice, you can join your data using comparison operators on join condition. Then, take the difference between two years, sort the difference ascending and pick the first result using ROW_NUMBER() function. See example:

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