sql server把退款總金額拆分到儘量少的多個訂單中詳解
阿新 • • 發佈:2020-12-17
一、問題
原來有三個充值訂單,現在要退款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,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
四、指令碼執行結果
總結
到此這篇關於sql server把退款總金額拆分到儘量少的多個訂單中的文章就介紹到這了,更多相關sql server退款總金額拆分到訂單內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!