如何在Sql Server中将数字字段拆分为较小的段

时间:2015-07-01 14:47:48

标签: sql-server split group-by tile

我在SQL Server中有一个包含两个字段的表。

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

2 个答案:

答案 0 :(得分:7)

这应该这样做:

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表,你可以删除那个部分。我正在使用spt_values就像我知道其中有很多行的表一样,所以{{1表达式应该生成所有必要的数字)

结果:

ROW_NUMBER()

答案 1 :(得分:0)

我使用SQL CTE expressionSQL 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