sql server如何把退款總金額拆分到盡量少的多個訂單中


一、問題

原來有三個充值訂單,現在要退款450元,如何分配才能讓本次退款涉及的充值訂單數量最少?具體數據參考下圖:

二、解決方案

  • Step 1:對可退金額進行降序排列,以便優先使用可退金額比較大的訂單
  • Step 2:使用CTE公用表達式,遞歸方式實現類似for或while循環或游標的功能

三、腳本

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 可發起退款, 0 待退
    from #t
),
cte2 as
(
    select rn, 充值, 已退, 可退, 
        可發起退款 = case when @i要退 > 可退 then 可退 else @i要退 end, 
        待退 = @i要退 - case when @i要退 > 可退 then 可退 else @i要退 end -- 待退 = 要退 - 可發起退款
    from cte1
    where rn = 1
    union all
    select t2.rn, t2.充值, t2.已退, t2.可退,
        可發起退款 = 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

四、腳本運行結果

五、作者聲明

歡迎轉載,但轉載請務必注明博文來源和作者!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM