繁体   English   中英

选择SUM大于X的行

[英]Select row where SUM becomes greater than X

我有这张桌子

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

我想选择总和(持续时间)大于15的id。换句话说......

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

Sum在ID为2的行中变得更加严格。我必须准确选择此行。

当然我不能从存储过程中使用SUM(),所以我必须使用JOIN并且可能使用HAVING而不是WHERE。 问题是我总是得到错误的结果。

要做到这一点,您需要一个累积总和,MySQL不直接提供。 您可以使用子查询来完成此操作。 然后选择右侧行。

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

请注意,当多行具有相同的持续时间时,此命令按id排序。

检查SQLFiddle以获取备用解决方案。

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

试试这个查询

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

将保证正确的持续时间值

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

一个更简单的解决方案只有在有一个组时才有效,如果你想要总组明智则必须在查询中进行一些更改

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 |

暂无
暂无

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

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