時間:2024-02-13 10:23作者:下載吧人氣:17
原來有三個充值訂單,現(xiàn)在要退款450元,如何分配才能讓本次退款涉及的充值訂單數(shù)量最少?具體數(shù)據(jù)參考下圖:
Step 1:對可退金額進行降序排列,以便優(yōu)先使用可退金額比較大的訂單
Step 2:使用CTE公用表達式,實現(xiàn)類似for或while循環(huán)或游標(biāo)的功能
create table #t
(
充值 int,
已退 int,
可退 int
)
insert into #t(充值, 已退, 可退)
values (200, 100, 100), (500, 200, 300), (300, 100, 200)
/*
作者:zhang502219048
腳本來源:https://www.cnblogs.com/zhang502219048/p/14127208.html
*/
declare @i要退 int = 450;
with cte1 as
(
select *, row_number() over(order by 可退 desc) rn, 0 可發(fā)起退款, 0 待退
from #t
),
cte2 as
(
select rn, 充值, 已退, 可退,
可發(fā)起退款 = case when @i要退 > 可退 then 可退 else @i要退 end,
待退 = @i要退 – case when @i要退 > 可退 then 可退 else @i要退 end — 待退 = 要退 – 可發(fā)起退款
from cte1
where rn = 1
union all
select t2.rn, t2.充值, t2.已退, t2.可退,
可發(fā)起退款 = case when t1.待退 > t2.可退 then t2.可退 else t1.待退 end,
待退 = t1.待退 – case when t1.待退 > t2.可退 then t2.可退 else t1.待退 end
from cte1 t2
inner join cte2 t1 on t1.rn = t2.rn – 1 — t2是t1的下一條記錄
–where t2.rn > 1 and t1.待退 > 0
)
select * from cte2
drop table #t
網(wǎng)友評論