Oracle min and max columns query
Alright, need some help created a query for an Oracle 10g DB. I have a table to looks like this:
----------------------------------------
| lowerBound | upperBound | locationId |
----------------------------------------
| 0 | 99 | 1 |
----------------------------------------
| 100 | 199 | 2 |
----------------------------------------
...
Another table looks like this:
-----------------------------
| locationId | locationCode |
-----------------------------
| 1 | 12345 |
-----------------------------
| 2 | 23456 |
-----------------------------
| 3 | 34567 |
-----------------------------
...
I start with a number, say 113, but it is a variable figured out in java. I need to figure out the locationId that corresponds to that number, based on it falling between the lowerBound and upperBound columns, and then join that to figu开发者_JAVA技巧re out the locationCode in the 2nd table. I've looked up things like MIN/MAX and between, however I am not finding exactly what I am looking for. I am not a good DBA, so any help is appreciated.
SELECT t2.locationCode
FROM table1 t1
INNER JOIN table2 t2 USING(locationId)
WHERE 113 BETWEEN t1.lowerBound AND t1.upperBound
If the USING part puzzles you:
SELECT t2.locationCode
FROM table1 t1
INNER JOIN table2 t2 ON t2.locationId = t1.locationId
WHERE 113 BETWEEN t1.lowerBound AND t1.upperBound
Note that this will work if your lowerBound and upperBound columns are INTEGERS. If they are VARCHAR, you will have to use the TO_NUMBER
function of course.
精彩评论