3

我有这张桌子

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

我想选择 sum(duration) 大于 15 的 id。换句话说...

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

总和在 ID 为 2 的行处变得更大。我必须准确地选择这一行。

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

4

3 回答 3

0

检查SQLFiddle以获取替代解决方案。

SELECT 
  id 
FROM 
  test1 
JOIN  
  (SELECT @rn := 0 ) r 
WHERE 
  (@rn := @rn + duration) > 15
于 2013-05-21T11:20:47.410 回答
0

试试这个查询

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 小提琴

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

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

SQL 小提琴

| ID | DURATION | TOT |
-----------------------
|  1 |       10 |  10 |
|  2 |       50 |  60 |
|  3 |       30 |  90 |
于 2013-05-21T12:04:01.857 回答
0

为此,您需要一个累积总和,这是 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当多行具有相同的持续时间时,此排序。

于 2013-05-21T10:58:14.677 回答