sql server把退款总金额拆分到尽量少的多个订单中详解

2022-05-23 0 1,057

一、问题

原来有三个充值订单,现在要退款450元,如何分配才能让本次退款涉及的充值订单数量最少?具体数据参考下图:

sql server把退款总金额拆分到尽量少的多个订单中详解

二、解决方案

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

四、脚本运行结果

sql server把退款总金额拆分到尽量少的多个订单中详解

总结

到此这篇关于sql server把退款总金额拆分到尽量少的多个订单中的文章就介绍到这了,更多相关sql server退款总金额拆分到订单内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MsSql sql server把退款总金额拆分到尽量少的多个订单中详解 https://www.niceym.com/59128.html