现有以下数据:1 2 3 5 6 8 9
需要的结果为:
最小值 | 最大值 | 连续数 |
1 | 3 | 3 |
5 | 6 | 2 |
8 | 9 | 2 |
实现Sql语句如下:
select 1 Value into #temp union all select 2 Value union all select 3 Value union all select 5 Value union all select 6 Value union all select 8 Value union all select 9 Value select row_number()over(order by Value) RowIndex,Value into #temp1 from #temp CREATE TABLE #result ( value1 int, value2 int, value3 int ) declare @Count int,@Index int,@BeginNun int,@EndNum int,@Num int,@NumCount int,@NewBegin int select @Count=COUNT(1) from #temp1 set @Index=1 set @BeginNun=0 set @NewBegin=1 while @Index<=@Count begin select @Num=Value from #temp1 where RowIndex=@Index --select @NewBegin,@Num if(@NewBegin=1) begin if (@BeginNun=0) begin set @BeginNun=@Num END set @EndNum=@Num set @NumCount=1 set @NewBegin=0 --select '新开始',@BeginNun,@EndNum,@NumCount end else begin if(@EndNum+1=@Num) begin set @NumCount=@NumCount+1 set @EndNum=@Num set @NewBegin=0 --select @BeginNun,@EndNum,@NumCount end else begin insert into #result(value1,value2,value3)values(@BeginNun,@EndNum,@NumCount) set @BeginNun=@Num set @NewBegin=1 --select @BeginNun,@EndNum,@NumCount end end if(@NewBegin<>1) begin set @Index=@Index+1 end if(@Index>@Count) insert into #result(value1,value2,value3)values(@BeginNun,@EndNum,@NumCount) end select * from #result drop table #temp,#temp1,#result