且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PostgreSQL 中查找序列中的间隙?

更新时间:2022-10-24 08:41:11

如果你想要缺失值的范围,那么:

选择 number_col + 1 作为 first_missing,(next_nc - 1) 作为 last_missingfrom (select t.*,lead(number_col) over (partition by id order by number_col) 作为 next_nc从T) t其中 next_nc <>number_col + 1

I have a table of items with an id and a number_col. There are plenty of questions on *** for finding gaps in IDs, but what I'm looking for is a gap in the number. For example, if I have 3 items:

id | number_col
===============
1  | 1
1  | 2
1  | 4

I need a SQL query that returns id = 1, number_col = 3 as missing. The query should look at the max value in number_col for each id. Since 4 is the max number_col value for id 1 in my example, it should not return that 1, 5 is missing.

If you want ranges of missing values, then:

select number_col + 1 as first_missing, (next_nc - 1) as last_missing
from (select t.*, lead(number_col) over (partition by id order by number_col) as next_nc
      from t
     ) t
where next_nc <> number_col + 1