SQL组按整数值的连续范围



我有一个表:

id  number  owner
47   100      1
48   101      1
49   102      1
50   103      2
51   104      2
52   105      2
53   106      1
54   107      1
55   108      2
56   109      2
57   110      2

如何按连续数字和所有者进行分组以获取结果:

from_number  to_number    owner
   100          102         1
   103          105         2
   106          107         1
   108          110         2

我尝试了: SELECT MIN(number), MAX(number), owner FROM table GROUP BY owner,但得到结果:

MIN(number)  MAX(number)  owner 
   100          107        1
   103          110        2

这是一种"组和岛"问题。您可以通过从number中减去序列来做到这一点。当number s顺序时,差异是恒定的:

select owner, min(number) as from_number, max(number) as to_number
from (select t.*,
             row_number() over (partition by owner order by number) as seqnum
      from t
     ) t
group by owner, (number - seqnum);

您可以通过生成两个行号并进行差异

尝试尝试
select owner, min(number) as min_number, max(number) as max_number
from (select a.*,
             row_number() over (partition by owner order by number) as rn1,
             row_number() over(order by number) rn2
      from table_name a
     ) t
group by owner, (rn2 - rn1);

相关内容

  • 没有找到相关文章

最新更新