add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE mytable(
item_id INTEGER NOT NULL PRIMARY KEY
,rate INTEGER NOT NULL
,status VARCHAR(6) NOT NULL
);
INSERT INTO mytable(item_id,rate,status) VALUES (1,12,'credit');
INSERT INTO mytable(item_id,rate,status) VALUES (2,10,'credit');
INSERT INTO mytable(item_id,rate,status) VALUES (3,10,'credit');
INSERT INTO mytable(item_id,rate,status) VALUES (4,20,'cash');
INSERT INTO mytable(item_id,rate,status) VALUES (5,55,'credit');

select item_id,
case when sum_rate >= 25 then 'credit' else 'cash' end as status,
case when sum_rate >= 25 then sum_rate - 25 else rate end as rate
from (
select t.*, sum(rate) over(order by item_id) sum_rate
from mytable t
where status = 'credit'
) t
where sum_rate - rate < 25
item_id status rate
1 cash 12
2 cash 10
3 credit 7
update mytable t
inner join (
select item_id, sum(rate) over(order by item_id) sum_rate
from mytable t
where status = 'credit'
) t1 on t1.item_id = t.item_id
set
t.status = case when sum_rate >= 25 then 'credit' else 'cash' end,
t.rate = case when t1.sum_rate >= 25 then t1.sum_rate - 25 else t.rate end
where t1.sum_rate - t.rate < 25
select * from mytable order by item_id
item_id rate status
1 12 cash
2 10 cash
3 7 credit
4 20 cash
5 55 credit