Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select till the sum reach some value

Tags:

sql

mysql

having this table

#table stock
+-------+----------+
|  id   |   stock  |
+-------+----------+
|   1   |    20    |
+-------+----------+
|   2   |    25    |
+-------+----------+
|   3   |    10    |
+-------+----------+
|   4   |    20    |
+-------+----------+
#note: this is an arbitrary random data

How can I keep selecting rows from the table till the sum() of the stock column reaches some value or a little higher , and the table is ORDER BY id ASC.

For example I want to select rows from the table till I have sum of stock '50' , so the result will be

#result 3 rows
+-------+----------+
|  id   |   stock  |
+-------+----------+
|   1   |    20    |
+-------+----------+
|   2   |    25    |
+-------+----------+
|   3   |    10    |
+-------+----------+

the sum of stock now is '55' which is the closest possible higher value than '50' , and if we take the next row id:4 the sum of stock will be higher than 50 , and if we remove the row id:3 the value will be 45 which is less than the stock I want 50 .

I can achieve this with PHP by selecting all the rows and loop throw them, but I guess that will be a waste. Is there a possible way to do that on a lower level and let mysql do that for me by a sql query?

Thank you and forgive me if I messed something , I'm new to programming

like image 675
Accountant م Avatar asked Apr 03 '17 17:04

Accountant م


People also ask

How do you sum in select?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do you select a row with maximum value?

MySQL select the row with maximum value in a column : MAX() function. This section will help us learn how to get the maximum value for a column and get the record details corresponding to it. Let us start by creating a table sales_details followed by inserting some records to it.

How do I select a certain number of rows?

Select one or more rows and columnsSelect the row number to select the entire row. Or click on any cell in the row and then press Shift + Space. To select non-adjacent rows or columns, hold Ctrl and select the row or column numbers.


1 Answers

You need a cumulative sum for this to work. One method uses variables:

select t.*
from (select t.*, (@sum := @sum + stock) as cume_stock
      from t cross join
           (select @sum := 0) params
      order by id 
     ) t
where cume_stock < 50 or (cume_stock >= 50 and cume_stock - stock < 50);
like image 198
Gordon Linoff Avatar answered Sep 16 '22 12:09

Gordon Linoff