SQL - find the correct value

55 views Asked by At

I've got this problem

in this table i've registered for each amount the relative discount

Amount   Discount
 500        5%
1000       10%
1200       11%
2100       15%

ecc...

In another table i've got the gross price of the order for example 2000 how i can find the correct discount for this order? In that case 11% because 2100 > 2000 ?

3

There are 3 answers

1
René Nyffenegger On
select discount
  from tq84_discount
 where amount = (
  select max(amount)
   from tq84_discount
  where amount <= 2000
 );

Test data:

create table tq84_discount (
  amount number,
  discount number
);

insert into tq84_discount values (  0, 0);
insert into tq84_discount values (500, 5);
insert into tq84_discount values (100, 10);
insert into tq84_discount values (1200, 11);
insert into tq84_discount values (2100, 15);
0
Giorgi Nakeuri On

With top:

select top 1 Discount 
from Discounts
where Amount <= 2000
order by Amount desc
0
Novice Programmer On
select top 1 Discount
from Discounts
where Amount < GrossPrice
orderby Amount desc

This simple query works. GrossPrice is the variable in which it has the value from other table. 2000 in this case.