如何用T-SQL基于除法与余数生成批次行?求助
最优T-SQL实现:按批次拆分总数为多行数据
已知变量声明:
declare @Total int = 203; declare @Batch int = 100;
需要生成如下结果集:
100 100 3
给你两种高效的实现方式:
方法一:递归CTE(简洁直观,适合小数量场景)
这种写法不需要依赖额外的表,逻辑清晰:
declare @Total int = 203; declare @Batch int = 100; with BatchCTE as ( select -- 第一个批次值:总数大于批次量则取批次量,否则取总数 case when @Total > @Batch then @Batch else @Total end as BatchValue, -- 计算剩余数量 @Total - case when @Total > @Batch then @Batch else @Total end as Remaining union all select -- 后续批次:剩余量大于批次量则取批次量,否则取剩余量 case when Remaining > @Batch then @Batch else Remaining end, -- 更新剩余数量 Remaining - case when Remaining > @Batch then @Batch else Remaining end from BatchCTE -- 剩余量大于0时继续递归 where Remaining > 0 ) select BatchValue from BatchCTE;
方法二:利用系统数字表(性能更优,适合大数量场景)
如果需要处理的总数很大(比如几十万、几百万),递归CTE的层级开销会比较高,这时可以用系统自带的数字表来实现:
declare @Total int = 203; declare @Batch int = 100; select case -- 当前行对应的累计批次量未超过总数,输出完整批次值 when row_number() over(order by (select null)) * @Batch <= @Total then @Batch -- 最后一行输出剩余量 else @Total - ((row_number() over(order by (select null)) - 1) * @Batch) end as BatchValue -- 用系统数字表生成需要的行数,type='P'对应0到2047的连续数字 from master..spt_values where type = 'P' -- 生成的行数等于总批次的向上取整值 and number < ceiling(cast(@Total as decimal)/@Batch);
如果你的总数超过2047,可以自己创建一个包含更大连续数字的表,替换master..spt_values即可。
内容的提问来源于stack exchange,提问作者user2463808
相关产品推荐
相关产品推荐

