gpt4 book ai didi

SQL 按整数值的连续范围分组

转载 作者:行者123 更新时间:2023-12-03 14:59:23 24 4
gpt4 key购买 nike

我有一张像这样的 table :

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);

关于SQL 按整数值的连续范围分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com