Here’s a tricky problem I haven’t quite been able to get my head around. I’m using SQL Server 2008, and I have a sparse range table that looks like this:
Range Profession
----- ----------
0 Office Worker
23 Construction
54 Medical
Then I have another table with values that are within these ranges. I’d like to construct a query which joins these two tables and gives me the Profession value that is less than or equal to the given value. So let’s say my other table looks like this:
Value
29
1
60
Then I’d like my join to return:
Value Profession
----- ----------
29 Construction
1 Office Worker
60 Medical
(because 29>the 23 for Construction but <=the 54 for Medical)
Is there any way I can get SQL to bend to my will in this manner, short of actually blowing out the range table to include every possible value?
Thank you.
You could use CROSS APPLY:
It should be faster than using max and doesn’t need a max-range do be maintained.