Skip to content
Advertisement

JOIN with OR condition and use only MIN(Column)

I have two tables. Certain values from table t need to be matched with certain values of table m in order to identify a target value from table m.

Table t looks as follows.

Table m looks as follows.

The logic should be as follows: Column A from table t should be matched with column matchA from table m and so on. As you can see in the example, there can be multiple matches. In the first row of table t the value y of column B matches with the y of first row of table m in column matchB. However, the first row of table t also matches with the second row of table m with the z value in columns C and matchC. If this is the case, only the match with the lowest priority should be returned in the resultset. The value of the column targetValue should be shown.

I know how to do the matching, but I don’t know how to filter down to just the result with the lowest priority.

This is what I have so far.

This returns both matching rows. However, I only want the match with the lowest value in the column priority.

Advertisement

Answer

This looks like a good use-case for a lateral join — or APPLY in the language of SQL Server:

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