问题
I am trying to do a very simple range lookup in MS Access.
I basically have two tables:
I am looking for a query that will be able to go find the appropriate range of the salary and return the correct tax rate.
I started off with this as my base:
SELECT IIf(Salary Between 1000 And 2000,10,20)
FROM Employees;
But I am not making any sort of progress.
Any assistance will be greatly appreciated.
回答1:
One possible method is to use a correlated subquery, e.g.:
select e.*, (select top 1 t.taxrate from taxrates t where t.to > e.salary order by t.to)
from employees e
Or using between:
select e.*, (select top 1 t.taxrate from taxrates t where e.salary between t.to and t.from)
from employees e
Alternatively, you can use a left join in the following way:
select e.*, t.taxrate
from employees e left join taxrates t on (e.salary between t.to and t.from)
Note that MS Access cannot represent this type of join in query Design View (i.e. a join with 'calculated' join criteria as opposed to joining on equal field values), but this is still valid SQL which may be successfully evaluated by the JET database engine.
In all of the above, I've assumed that your tables are called Employees
& TaxRates
, change these to suit.
回答2:
Here is an alternative solution:
SELECT Salary.*, TaxRate.TaxRate
FROM Salary, TaxRate
WHERE Salary BETWEEN From and TO;
来源:https://stackoverflow.com/questions/58103334/return-a-value-from-a-range-in-ms-access