简体   繁体   English

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

[英]MySQL select upto first occurrence of condition matching

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

I need to select ids where first occurrence of summation of price is greater than or equal 55 matching from the bottom. 我需要选择ID,其中第一次出现的价格总和大于或等于55从底部匹配。 At this case -- I will have 4,3,2 ids selected. 在这种情况下 - 我将选择4,3,2个ID。

Well, this is kinda tricky for MySQL since it doesn't support any window fuctions and becuase you want to include the first occurrence as well. 嗯,这对MySQL来说有点棘手,因为它不支持任何窗口功能,因为你想要包括第一次出现。 You can try this: 你可以试试这个:

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

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

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