按顺序查找范围

时间:2019-03-29 11:04:52

标签: sql sql-server

我有表@NumberRange。它具有开始和结束编号。我必须找出范围是按顺序的

Declare @NumberRange table
(
    Id int primary key, 
    ItemId int,
    [start] int,
    [end] int
)


INSERT INTO @NumberRange
VALUES  
(1,1,1,10),
(2,1,11,20),
(3,1,21,30),
(4,1,40,50),
(5,1,51,60),
(6,1,61,70),
(7,1,80,90),
(8,1,100,200) 

预期结果:

enter image description here

注:如果任何连续数字(即1到10,11-20,21-30)是连续数字,则计算结果列。因此结果列更新为1,然后更新为41-50非连续数字(因为上一行以30结尾,下一行以40开头),这就是为什么结果列将是2并且是连续的。

在第四阶段以50结束,第五阶段以51连续开始,然后结果将为3,因为我与结果1有所区别...

我使用了lead函数,但未达到预期的结果,..请有人帮我得到结果吗?

解决方法:

select  
    *,
    [Diff] = [Lead] - [end], 
    [Result] = Rank() OVER (PARTITION BY ([Lead] - [end]) ORDER BY Id) 
from 
    (select 
         id, [start], [end], LEAD([start]) over (order by id) as [Lead] 
     from 
         @NumberRange) Z   
order by 
    id

2 个答案:

答案 0 :(得分:2)

使用lag()确定组的起始位置。然后累加和枚举它们:

select nr.*,
       sum(case when startr = prev_endr + 1  then 0 else 1 end) over (partition by itemid order by startr) as grp
from (select nr.*, lag(endr) over (partition by itemid order by startr) as prev_endr
      from numberrange nr
     ) nr;

Here是db <>小提琴。

此答案假设ID 4和ID 5是连续的,这对于其余问题是有道理的。

答案 1 :(得分:1)

您的预期结果不清楚,我的评论中也有疑问,但是我认为您想要做的事情与

类似
  * xml serviceGroupListItems = get xmlResponse //serviceGroupList
  * match each serviceGroupListItems == serviceGroupItem

enter image description here