I have this table
CREATE TABLE base_table (id int, amount int)
INSERT INTO base_table VALUES (1, 1)
,(2,1)
,(3,1)
,(4,1)
,(5,1)
,(6,2)
,(7,3)
The sum of first 5 amounts is equal to the sum of last two, I need to find this id 5.
I manage to do it with following query :
SELECT b.id
FROM base_table b, (SELECT SUM(amount)/2 AS amount FROM base_table) s
WHERE (SELECT SUM(amount) FROM base_table b2 WHERE b2.id <= b.id ) <= s.amount
AND (SELECT SUM(amount) FROM base_table b3 WHERE b3.id <= b.id + 1) > s.amount
Now this query will perform badly for big tables (I have not tried). What can we do to improve performance ?