简体   繁体   English

选择SUM大于X的行

[英]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... 我想选择总和(持续时间)大于15的id。换句话说......

-------------------------
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. Sum在ID为2的行中变得更加严格。我必须准确选择此行。

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. 当然我不能从存储过程中使用SUM(),所以我必须使用JOIN并且可能使用HAVING而不是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. 要做到这一点,您需要一个累积总和,MySQL不直接提供。 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. 请注意,当多行具有相同的持续时间时,此命令按id排序。

Check SQLFiddle for alternate solution. 检查SQLFiddle以获取备用解决方案。

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 : 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 : SQL FIDDLE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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