[英]How Do I Find a Gap In a Sequence in PostgreSQL?
I have a table of items with an id and a number_col.我有一个带有 id 和 number_col 的项目表。 There are plenty of questions on Stackoverflow for finding gaps in IDs, but what I'm looking for is a gap in the number.
在 Stackoverflow 上有很多关于寻找 ID 差距的问题,但我正在寻找的是数字差距。 For example, if I have 3 items:
例如,如果我有 3 个项目:
id | number_col =============== 1 | 1 1 | 2 1 | 4
I need a SQL query that returns id = 1, number_col = 3 as missing.我需要一个返回 id = 1, number_col = 3 作为缺失的 SQL 查询。 The query should look at the max value in number_col for each id.
查询应该查看每个 id 的 number_col 中的最大值。 Since 4 is the max number_col value for id 1 in my example, it should not return that 1, 5 is missing.
由于在我的示例中 4 是 id 1 的最大 number_col 值,因此它不应返回 1, 5 丢失。
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
you can use this query你可以使用这个查询
select * from table_name where col_name - 1 NOT IN (select col_name from table_name) GROUP BY col_name having col_name > MIN(col_name); select * from table_name where col_name - 1 NOT IN (select col_name from table_name) GROUP BY col_name has col_name > MIN(col_name);
GROUP BY col_name having col_name > MIN(col_name) to discard the first row. GROUP BY col_name 具有 col_name > MIN(col_name)以丢弃第一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.