I want to write a query which returns all rows until the sum of one of the columns value reaches a certain value.
For example in the table below:
DATE ETC Meeting
2013-02-01 00:00:00 85482 1
2013-02-01 00:00:00 47228 2
2013-02-02 00:00:00 12026 4
2013-02-03 00:00:00 78927 6
2013-02-04 00:00:00 85662 2
2013-03-05 00:00:00 47978 1
2013-08-07 00:00:00 8582 1
If I want to get the rows until the sum of column Meeting
equals 7.
DATE ETC Meeting
2013-02-01 00:00:00 85482 1
2013-02-01 00:00:00 47228 2
2013-02-02 00:00:00 12026 4
If I want to get the rows until the sum of column Meeting
equals 13.
DATE ETC Meeting
2013-02-01 00:00:00 85482 1
2013-02-01 00:00:00 47228 2
2013-02-02 00:00:00 12026 4
2013-02-03 00:00:00 78927 6
In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.
In SQL, we use the SUM() function to add the numeric values in a column. It is an aggregate function in SQL. The aggregate function is used in conjunction with the WHERE clause to extract more information from the data.
To limit rows in the result set, use ORDER BY with the optional OFFSET and FETCH clauses. First, the query sorts the rows (ORDER BY). You then tell SQL Server which should be the first row in the result set (OFFSET... ROWS) and how many rows to return (FETCH…
You can easily change this limit by going to MySQL Workbench >> Edit >> Preferences >> SQL Queries tab. Over here you will option to Limit Rows. You can set this to very high value or uncheck the option. When you uncheck that option, it will retrieve all the rows from a query (equivalent to no limits).
Here's a way to do it without a stored procedure:
SET @msum := 0;
SELECT t1.*
FROM (
SELECT m.*,
(@msum := @msum + m.meetings) AS cumulative_meetings
FROM meetings m
ORDER BY m.date ASC
) t1
WHERE t1.cumulative_meetings <= 7;
Here's a way which should work in MySQL :
SELECT
O.Id,
O.Type,
O.MyAmountCol,
(SELECT
sum(MyAmountCol) FROM Table1
WHERE Id <= O.Id) 'RunningTotal'
FROM Table1 O
HAVING RunningTotal <= 7
It involves calculating a running total and selecting records while the running total is less than or equal to the given number, in this case 7
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With