我正在使用 MySQL 5.5 来存储如下表:
sequence category value
1 A 100
2 A 200
3 A -300 # sum becomes 0
4 B 200
5 B 500
对于每个类别,我想找到导致sum(value)
该类别降至 0 以下的第一条记录(按顺序排序)。
我目前的解决方案是(SQL函数伪代码):
create function find_low_value(in_category) returns int
begin
declare cursor select sequence, value from table where category = in_category;
declare sum int default 0;
open and fetch cursor;
set sum = sum + value;
if sum <= 0 then
return sequence;
end if;
end
但效率不高。有更好/更简单的解决方案吗?
谢谢。