问题
item_id rate status
--------- ----------- ------
1 12 credit
2 10 credit
3 10 credit
4 20 cash
5 55 credit
I have the above table, A user inputs and amount of 25. Now I want to update the status of the rows having credit as status from credit to cash until the sum of rate is 25, so in the above table the top 1 rows having a sum of 22 should get a status of cash. Since the user input is 25, I still have a balance of 3 (25-22), this balance should be deducted from the third row making the third row rate 7. The result I want is tabular form with the changes highlighted:
item_id rate status
--------- ----------- ------
1 12 **cash**
2 10 **cash**
3 **7** credit
4 20 cash
5 55 credit
回答1:
You can use window functions to identify the rows that need to be changed:
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
You can put that logic in an update
statement if you prefer:
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
Demo on DB Fiddle
来源:https://stackoverflow.com/questions/65135819/select-sum-until-a-set-amount-and-then-update-fields-in-mysql-database