简体   繁体   中英

Select row where SUM becomes greater than X

I have this table

----------------
ID    | Duration 
----------------
1       10       
2       10      
3       10       

I want to select the id where sum(duration) becomes greater than 15. In other words...

-------------------------
ID    | Duration | Sum
-------------------------
1       10         10
2       10         20
3       10         30

Sum becomes grater at row with ID 2. I have to select exactly this row.

Of course i can't use SUM() from a stored procedure so for sure i have to use a JOIN and probably an HAVING instead of WHERE. The problem is that i always get the wrong result.

To do this, you need a cumulative sum, which MySQL does not offer directly. You can do that with a subquery. Then select the right row.

select id, duration, cumdur
from (select id, duration,
             (select sum(duration)
              from t t2
              where t2.duration < t.duration or
                    (t2.duration = t.duration and t2.id <= t.id)
             ) as cumdur
      from t
     ) t
where 15 between (cumdur - duration + 1) and cumdur

Note that this orders by id when multiple rows have the same duration.

Check SQLFiddle for alternate solution.

SELECT 
  id 
FROM 
  test1 
JOIN  
  (SELECT @rn := 0 ) r 
WHERE 
  (@rn := @rn + duration) > 15

Try this query

select a.id, a.duration, sum(b.duration) as tot
from 
tbl a 
inner join
tbl b 
On
a.id>=b.id
group by a.id

Will guarantee correct duration value

select a.id, a.duration, b.tot
from 
tbl a 
inner join 
(select a.id, sum(b.duration) as tot
from 
tbl a 
inner join
tbl b 
On
a.id>=b.id
group by a.id)
b
on a.id=b.id

SQL FIDDLE :

A simpler solution will work only if the there is one group, if you want the total group wise then have to make some changes in the query

select a.id, a.duration , @tot:=@tot+a.duration as tot
from 
tbl a 
join 
(select @tot:=0)tmp

SQL FIDDLE :

| ID | DURATION | TOT |
-----------------------
|  1 |       10 |  10 |
|  2 |       50 |  60 |
|  3 |       30 |  90 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM