I think I understand your problem. I created a table called professions with your values ββand a map_vals table with search values. Then I came up with this:
select p.range as `range1`, p.profession, v.value from professions p inner join map_vals v ON v.value >= p.range where p.range = (select max(p3.range) from professions p3 where p3.range <= v.value) order by v.value
which when setting these values ββ...
value 29 0 60 1 23 54
returns
range1 profession value 0 Office Worker 0 0 Office Worker 1 23 Construction 23 23 Construction 29 54 Medical 54 54 Medical 60
EDIT:
You can also use CROSS APPLY, as shown by manfred-sorg , but this requires ORDER BY DESC , or you will get the following:
select v.Value, p.Profession from tblValues v cross apply (select top(1) pr.Profession from tblProfessionRanges pr where pr.Range <= v.Value) p
produces
Value Profession ----------- -------------------------------------------------- 29 Office Worker 1 Office Worker 60 Office Worker
to get the desired result, you need to change it to:
select v.Value, p.Profession from tblValues v cross apply (select top(1) pr.Profession from tblProfessionRanges pr where pr.Range <= v.Value ORDER BY pr.[Range] DESC) p Value Profession
However, the required sorting makes it less efficient than using MAX .
source share