Select records with values ​​before and after (but only one) another value?

I have data such as ...

 ID    | Amount
-----------------
 1     | 50.00
 2     | 40.00
 3     | 15.35
 4     | 70.50

etc .. And I have a value I'm working on, in this case let's say 100.00. I want to get all records before 100.00 in order of identifier. And I want to capture one more, because I want to fill it with the goal that I was striving for.

That is, I want to get records 1, 2 and 3 in this example. The first two are only up to 90.00, and 3 is only 100.00. So I want the request to do this for me. Is there such a thing in MySQL, or will I have to resort to the loop of a PHP array?

Edit : To express this in English, let's say they have $ 100 in their account. I want to know which of their requests can be paid, either in full or in part. Therefore, I can pay $ 50 and $ 40, as well as part of $ 15.35. At this point in the program, I don't care about partiality; I just want to know what quality anyway.

+3
source share
2 answers

Yes maybe

 set @total:=0; 
 select * from
 (
   select *, if(@total>100, 0, 1) as included, @total:=@total+Amount 
   from your_table 
   order by id
 ) as alls
 where included=1
 order by id;
+4
source

Referring to the last sentence: doesn't mysql sumcut it off?

0
source

Source: https://habr.com/ru/post/1780528/


All Articles