Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query: find in which range quantity resides and then get the price of max quantity in the range

Tags:

mysql

Need a help in building query. I have quantity_price table, listing quantity and corresponding price as shown below

Quantity  Price
----------------
1   --  € 175,35
2.5 --  € 160,65
5   --  € 149,10
10  --  € 143,85

so for upto 1 quantity price will be 175,35 up to 2.5 it will be 160,65 and so on. For more than 10 quantity, price'll remain to 143,85.

Now if my quantity is 1.5 then query should return price 160,65, which means that find in which range quantity resides and then get the price of max quantity in the range.

like image 875
Asif Mulla Avatar asked Nov 05 '22 07:11

Asif Mulla


2 Answers

Use a where statement to find all rows bigger than 1.5; then use limit and order by to grab the row with the lowest quantity. As Petah commented, it's handy to always include the row with the largest quantity. For example:

select  *
from    quantity_price
where   Quantity > 1.5
        or Quantity = (select max(Quantity) from quantity_price)
order by
        Quantity
limit   1
like image 108
Andomar Avatar answered Nov 11 '22 06:11

Andomar


select price
from quantity_price
where myquantity >= quantity
order by quantity
limit 1
like image 21
Faisal Feroz Avatar answered Nov 11 '22 04:11

Faisal Feroz