Forum Moderators: open
I have a list of numbers that I need to check if they are in one of the ranges in the table, and if so grab the 3rd column.
For example, if the list was "1,6,11,16,21" I would want to return "'Range1','Range2'"
Actuallly, I would be even happier if it just verified that elements "1,11" returned matches.
Is there an easy way to do this within a single query? Or do I have to loop over the list and do a query for each element in the list? The table has about 15,000 records and the lists will run 4,000-8,000 elements. So I would much prefer to figure out some way to do it with just 1 database call instead of 1 call for each element!
value ¦ range
1 ¦ range1
2 ¦ range1
6 ¦ No Range Found
Type of thing.
I was thinking if you could loop through the logic to dynamically create SQL that you could run you could create a big union statement that would return the data all in one record set.
So something like:
sql = ''
for value_to_check in [1,2,6]:
sql = sql + """
Select
..case
....when
......value_to_check >= (select low_range1 from range_table) and value_to_check <= (select high_range1 from range_table)
....then
......value_to_check as value
......'Range1' as range
....when
......value_to_check >= low_range2 and value_to_check <= high_range2
....then
......value_to_check as value
......'Range2' as range
....when
......value_to_check >= low_range3 and value_to_check <= high_range3
....then
......value_to_check as value
......'Range3' as range
....else
......value_to_check as value
......'No Range Found' as range
**Unless end loop** 'Union All'
"""
Not sure if this is what you are looking for. If not I am willing to take another stab at it with you.
We finally decided to just brute force it and loop through the list. We dumped the data from the table into a temp table (instead of hitting the database table each trip through the loop) and ran some tests. The performance wasn't as bad as we feared, so I guess we'll stick with the brute force method.
Thanks anyway!