我有一个像这样的表
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
答案 0 :(得分:2)
这是一种“群岛”问题。您可以通过从number
中减去一个序列来实现。当number
是连续的时,差异是恒定的:
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);
答案 1 :(得分:0)
您可以尝试生成两个行号并求和它们的差异
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);