选择总经过值小于或等于的行

时间:2014-11-03 13:29:51

标签: mysql sql innodb

id | name | elapsed
1 James 0
2 John 60
3 Kerry 60
4 Janet 60
5 Katie 60

根据上述结果,如何选择'经过'总值小于或等于120的名称?对于那些结果,这将涉及选择名称'詹姆斯','约翰'和'克里'。如果我将经过的总数改为180,那么它也会选择“珍妮特”。

如何构建一个返回此内容的查询?

3 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT 
    t1.id, 
    t1.name, 
    t1.elapsed
FROM your_table t1
INNER JOIN your_table t2 ON (t1.id >= t2.id)
GROUP BY t1.id, t1.name, t1.elapsed
HAVING SUM(t2.elapsed) <= 120

答案 1 :(得分:1)

这里需要考虑的事情......

 SELECT * FROM ints;
 +---+
 | i |
 +---+
 | 0 |
 | 1 |
 | 2 |
 | 3 |
 | 4 |
 | 5 |
 | 6 |
 | 7 |
 | 8 |
 | 9 |
 +---+

 SELECT i,@x:=@x+i running FROM ints i,(SELECT @x:=0)var ORDER BY i;
 +---+----------+
 | i | running  |
 +---+----------+
 | 0 |        0 |
 | 1 |        1 |
 | 2 |        3 |
 | 3 |        6 |
 | 4 |       10 |
 | 5 |       15 |
 | 6 |       21 |
 | 7 |       28 |
 | 8 |       36 |
 | 9 |       45 |
 +---+----------+

答案 2 :(得分:0)

SELECT
    *
FROM (
    SELECT '1' AS ID, 'James' AS Name, 0 AS Elapsed
    UNION ALL SELECT '2', 'John', 60
    UNION ALL SELECT '3', 'Kerry', 60
    UNION ALL SELECT '4', 'Janet', 60
    UNION ALL SELECT '5', 'Katie', 60
) AS X
WHERE 1=1
    AND (
        SELECT SUM(Elapsed)
        FROM (
            SELECT '1' AS ID, 'James' AS Name, 0 AS Elapsed
            UNION ALL SELECT '2', 'John', 60
            UNION ALL SELECT '3', 'Kerry', 60
            UNION ALL SELECT '4', 'Janet', 60
            UNION ALL SELECT '5', 'Katie', 60
        ) AS Y
        WHERE Y.ID <= X.ID
    ) <= 180
ORDER BY ID