MySQL选择第一次出现条件匹配

时间:2016-06-05 10:27:16

标签: mysql

Id      | Price
----------------
1       | 10
2       | 20
3       | 40
4       | 10

我需要选择ID,其中第一次出现的价格总和大于或等于55匹配从底部。在这种情况下 - 我将选择4,3,2个ID。

1 个答案:

答案 0 :(得分:0)

嗯,这对MySQL来说有点棘手,因为它不支持任何窗口功能,因为你想要包括第一次出现。你可以试试这个:

SELECT * FROM (
    SELECT t.id,
           (SELECT sum(s.price) FROM YourTable s
            WHERE s.id <= t.id) as cuml_sum
    FROM YourTable t) ss
WHERE ss.cuml_sum < 55
--Will select all the record will the sum < 55
UNION ALL
SELECT * FROM (
    SELECT t.id,
           (SELECT sum(s.price) FROM YourTable s
            WHERE s.id <= t.id) as cuml_sum
    FROM YourTable t) tt
WHERE tt.cuml_sum >= 55
ORDER BY tt.cuml_sum 
LIMIT 1
--Will select the first record that have sum >= 55