sql server把退款總金額拆分到盡量少的多個訂單中詳解
發(fā)布日期:2021-12-08 20:48 | 文章來源:腳本之家
一、問題
原來有三個充值訂單,現(xiàn)在要退款450元,如何分配才能讓本次退款涉及的充值訂單數(shù)量最少?具體數(shù)據(jù)參考下圖:
二、解決方案
Step 1:對可退金額進行降序排列,以便優(yōu)先使用可退金額比較大的訂單
Step 2:使用CTE公用表達式,實現(xiàn)類似for或while循環(huán)或游標的功能
三、腳本
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
四、腳本運行結(jié)果
總結(jié)
到此這篇關(guān)于sql server把退款總金額拆分到盡量少的多個訂單中的文章就介紹到這了,更多相關(guān)sql server退款總金額拆分到訂單內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章