Skip to content
Advertisement

Select closest maximal numeric value in Firebird

Imagine there’re 2 tables, let’s call them “Master” and “Detail”:

There’re 2 input parameters: list of Master IDs (master_id_list) and numeric value (num_value).

For every ID in master_id_list I should get one Detail record:

  1. If num_value < MIN( f_value ), it should be the record with MIN( f_value )
  2. If num_value > MAX( f_value ), it should be the record with MAX( f_value )
  3. Otherwise it should be the record with the closest maximal f_value

Example1. master_id_list = [ 1, 2 ], num_value = 0. Result:

Example2. master_id_list = [ 1, 2 ], num_value = 50. Result:

Example3. master_id_list = [ 1, 2 ], num_value = 0.94. Result:

Is it possible with one single SQL query? I’ve tried to “play” with solutions here and here but failed.

Advertisement

Answer

Let’s call num_value your needle (as in, “needle in the haystack”) that you’re looking for.

First we’ll normalize the needle so that it is no lower than the MIN(f_value) and no higher than the MAX(f_value) for each master_id.

Then we’ll look for each Detail row with the nearest f_value that’s greater than or equal to our normalized needle, grouped by master_id. (This is then just a greatest-n-per-group sql problem).

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