Skip to content
Advertisement

Join on multiple columns and in one of the integer columns join by choosing minimum difference

I got table t1 and i want to join it with table t2 below on columns a, b and c

t2

When I join only on a and c the result is

What I try to achieve is to add column b to ‘on’ clause so that join happens on minimum difference in b column.

Desired result

I saw something similar here

https://dba.stackexchange.com/questions/73804/how-to-retrieve-closest-value-based-on-look-up-table

but not sure how to apply to my case.

Advertisement

Answer

Join the tables and calculate the differences for column c, then use distinct on to return only one row per (a, c) ordered by the difference.

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