简体   繁体   中英

SQL Query to return a value based on data in a range

I have two tables - list of customers with a total next to them, they also have a type column and a status record.

For example

CustomerName, TotalOR, Type, Status
Customer 1, 205, P, Maint
Customer 2, 199, S, Maint

and a second table with the details with the service band in which they fall.

Band, Type, Status, TotalORFrom, TotalORTo
B1, P, Maint, 1, 199
B2, P, Maint, 199, 300
B3, S, Maint, 1, 199

What I want to be able to do is return the Band for each customer based on the customers TotalOR, Type and Status.

I have tried to create multiple queries which I can get it to return all possible bands, but not the specific band. Any help would be very much appreciated.

Thanks

Assuming the first table is customer and the second table is band :

SELECT band
FROM customer c
JOIN band b ON c.Type = b.Type
AND c.Status = b.Status
AND (c.TotalOR = b.TotalORFrom OR c.TotalOR = b.TotalORTo)

Edit: I can't tell if you're trying to join based on TotalORFrom or TotalORTo , so this query joins based on either one being the same.

Edit 2: Based on your comment, here is a new query that ensures customer.TotalOR is-greater-than-or-equal to band.TotalORFrom and customer.TotalOR is less-than-or-equal-to band.TotalORTo .

SELECT band
FROM customer c
JOIN band b ON c.Type = b.Type
AND c.Status = b.Status
AND c.TotalOR BETWEEN b.TotalORFrom AND b.TotalORTo

UPDATE: the above seems to cause an overlap of B1 and B2 at 199 for P, Maint . Consider this alternative to eliminate the overlap:

SELECT band
FROM customer c
JOIN band b ON c.Type = b.Type
AND c.Status = b.Status
AND c.TotalOR >= b.TotalORFrom
AND c.TotalOR < b.TotalORTo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM