使用sql中的cte创建范围

时间:2014-04-23 12:15:44

标签: sql sql-server-2008-r2 common-table-expression

我有一个只有单列的表,其值如下:

declare @numberrange table 
(
  num int 
)

insert into @numberrange (num) 
 values(24) ,
 (29) ,
( 34 ),
( 39 ),
( 44 ),
( 49 ),
( 54 ),
( 59  ),
( 64  ),
( 69  ),
( 74  ),
( 99 )

现在我想显示结果如下

24  24-29
29  30-34
34  35-39
39  40-44
44  45-49
49  50-54
54  55-59
59  60-64
64  65-69
69  70-74
74  75-99
99

我尝试过使用sql cte函数但无法获得所需的结果。

1 个答案:

答案 0 :(得分:1)

您可以使用此CTE查询。查询构建了最后一条记录的范围,以便最后一条记录具有空范围,第一条记录具有范围。

;with cte
as
(
    select top 1 num, sortorder, convert(varchar(21), null) rangevalue
    from (select num, ROW_NUMBER() over (order by num) as sortorder from @numberrange) x
    order by sortorder desc

    union all

    select x.num, x.sortorder, convert(varchar(10), x.num) + '-' + convert(varchar(10), cte.num)
    from (select num, ROW_NUMBER() over (order by num) as sortorder from @numberrange) x
    inner join cte
    on cte.sortorder = x.sortorder + 1
)

select num, rangevalue from cte
order by num