Something like this:
SELECT t.itemnumber,
MIN( b.binnumber ) KEEP ( DENSE_RANK LAST ORDER BY b.current_balance ASC ) AS binnumber
FROM item_table t
LEFT OUTER JOIN inventory_balance b
ON ( t.itemnumber = b.itemnumber )
GROUP BY t.itemnumber;
Looking at the explain plan then this will only scan inventory_balance
once whereas doing nested selects to get the MAX
balance and then filter an outer query based on that requires two scans of inventory_balance
.
Although all the required output for you minimal working example seems to be contained in the inventory_balance
table so you can do (if you are not interested in the itemnumber
s where there are no entries in the inventory_balance
table):
SELECT itemnumber,
MIN( binnumber ) KEEP ( DENSE_RANK LAST ORDER BY current_balance ASC ) AS binnumber
FROM inventory_balance
GROUP BY itemnumber;
If you want the highest binnumber
(instead of the lowest) then you can just change it to:
MAX( binnumber ) KEEP ...