I have a table with only single column which have values like as follow

declare @numberrange table 
(
  num int 
)

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

Now i want to show the result like as follow

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

i have tried with sql cte function but not able to get the desired result.

有帮助吗?

解决方案

You can use this CTE query. The query builds the range from the last record so that the last record has empty range and the first one has a range.

;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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top