如果中间缺少数字,则获取数字列的范围(min/max)

getting the range of a number column(min/max) if there are missing numbers in between

如果某个数字在某处结束然后又以更高的数字再次出现,我将如何查询数字列的范围?

如果我有这样的专栏:

Number
-------
 1
 2
 3
 4
 5
 11
 12
 13

我怎样才能return得到像

这样的结果
Min | Max
----------
 1  |  5
 11 |  13
;WITH CTE AS
(
 SELECT 
   Number, 
   Number - dense_rank() over (order by Number) grp
 FROM yourtable
)
SELECT min(Number) min, max(Number) max
FROM CTE
GROUP BY grp

FIDDLE

试试这个:

select t1.num, (select min(num) from table t3
                where t3.num >= t1.num
                  and t3.num + 1 not in (select num from table))
from table t1
where not exists (select * from table t2
                  where t1.num - 1 = t2.num)

where 子句仅查找不同范围的最小值。

子select 找到没有值的最低值 + 1 个可用值。

另一种方法:

select n1.number as min,min(n2.number) as max
from table n1 
JOIN table n2 ON n1.number<n2.number 
AND NOT EXISTS (select 1 from number where number = n1.number-1)
AND  NOT EXISTS (select 1 from number where number=n2.number+1)
group by n1.number
order by n1.number