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:
This one outperforms all.
SET @runningTotal=0; SELECT O.Id, O.Type, O.MyAmountCol, @runningTotal + O.MyAmountCol as 'RunningTotal', @runningTotal := @runningTotal + O.MyAmountCol FROM Table1 O HAVING RunningTotal <=7;
SQL Fiddle
Take a look at execution plans for both queries.