我正在使用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
但效率不高。有更好/更简单的解决方案吗?
感谢。
答案 0 :(得分:3)
我不知道这是否算得上“更好/更简单”,但您可以将其编写为常规SQL查询:
SELECT MIN(sequence)
FROM ( SELECT t1.sequence
FROM table_name t1
JOIN table_name t2
ON t2.category = t1.category
AND t2.sequence <= t1.sequence
WHERE t1.category = ...
GROUP
BY t1.sequence
HAVING SUM(t2.value) <= 0
)
;
答案 1 :(得分:0)
按类别从测试组中选择min(id),category,sum(value)作为total_sum 有total_sum&lt; = 0