1. 程式人生 > >sql server如何把退款總金額拆分到儘量少的多個訂單中

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

### 一、問題 原來有三個充值訂單,現在要退款450元,如何分配才能讓本次退款涉及的充值訂單數量最少?具體資料參考下圖: ![](https://img2020.cnblogs.com/blog/1703141/202012/1703141-20201212222947767-462955423.png) ### 二、解決方案 * 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 ``` ### 四、指令碼執行結果 ![](https://img2020.cnblogs.com/blog/1703141/202012/1703141-20201212232342851-1890639840.png) ### 五、作者宣告 歡迎轉載,但轉載請務必註明博文來源和作者! * 來源 * https://www.cnblogs.com/zhang502219048/p/14127208.html * 作者 * 部落格園博主:zhang502219048 * 微信公眾號 * 關注此名稱:SQL資料庫程式設計 * 微訊號:zhang5