limiting the rows to where the sum a column equals a certain value in MySQL

前端 未结 8 2349
闹比i
闹比i 2020-11-29 08:32

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:

           


        
8条回答
  •  遥遥无期
    2020-11-29 09:26

    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.

提交回复
热议问题