如何在 Sql 服务器中将数字字段拆分为更小的段

How to split a numeric field into smaller segments in Sql Server

我在 SQL 服务器中有一个 table 有两个字段。

Total      Group
35645      24
12400      55
30000      41

我想将每个组拆分为固定大小为 7000 的较小段,每个组的其余部分放入最后一个段。所以,输出应该如下所示。

Segment  Total     Group
1        7000       24
2        7000       24
3        7000       24
4        7000       24
5        7000       24
6        645        24
1        7000       55
2        5400       55
1        7000       41
2        7000       41
3        7000       41
4        7000       41
5        2000       41

应该这样做:

declare @t table (Total int,[Group] int)
insert into @t(Total,[Group]) values
(35645,24 ),
(12400,55 ),
(30000,41 )
;With Numbers as (
    select ROW_NUMBER() OVER (ORDER BY number)-1 n
    from master..spt_values
)
select
    n.n+1 as Segment,
    CASE WHEN (n.n+1)*7000 < t.Total THEN 7000
    ELSE t.Total - (n.n*7000) END as Total,
    t.[Group]
from
    @t t inner join
    Numbers n on n.n*7000 < t.Total

(如果你已经有一个 Numbers table 你可以去掉那部分。我使用 spt_values 就像我知道的 table 有很多其中的行,以便 ROW_NUMBER() 表达式应该生成所有必要的数字)

结果:

Segment              Total                Group
-------------------- -------------------- -----------
1                    7000                 24
2                    7000                 24
3                    7000                 24
4                    7000                 24
5                    7000                 24
6                    645                  24
1                    7000                 55
2                    5400                 55
1                    7000                 41
2                    7000                 41
3                    7000                 41
4                    7000                 41
5                    2000                 41

我使用 SQL CTE expression and SQL numbers table 函数

准备了以下 SELECT 语句
declare @divisor int = 7000
;with CTE as (
select 
    Total, 
    [Group],
    @divisor divisor,
    (Total / @divisor) quotient,
    (Total % @divisor) reminder
from t
), NT as (
    SELECT i FROM dbo.NumbersTable(1, (select max(quotient) from CTE) ,1)
)
select
    case when i = 0 then reminder else divisor end as Total,
    [Group]
from (

    select * 
    from CTE, NT
    where quotient >= i

    union all

    select *, 0 as i
    from CTE
    where reminder >= 0

) t
order by [Group], i desc