PHP SQL Get the sum of 2 first records from table

How can I get the sum of the daily_rate_price field but only from the first two rows? Table name is daily_rates

daily_rate_id daily_rate_date daily_rate_price daily_rate_reservation
1480 2021-11-18 280.00 320
1481 2021-11-19 280.00 320
1482 2021-11-20 280.00 320

I tried something like this, but it apparently does not work:

$accomTotal=" SELECT SUM(daily_rate_price) AS accomTotal FROM daily_rates   
WHERE daily_rate_reservation=$reservationId  LIMIT 2 ;";

>Solution :

you need to use a subquery:

select sum(daily_rate_price) AS accomTotal 
from ( 
  select daily_rate_price from daily_rates 
  where daily_rate_reservation=$reservationId  
  order by daily_rate_date asc limit 2 
) t;

Leave a Reply