[英]How Do I Find a Gap In a Sequence in PostgreSQL?
我有一個帶有 id 和 number_col 的項目表。 在 Stackoverflow 上有很多關於尋找 ID 差距的問題,但我正在尋找的是數字差距。 例如,如果我有 3 個項目:
id | number_col =============== 1 | 1 1 | 2 1 | 4
我需要一個返回 id = 1, number_col = 3 作為缺失的 SQL 查詢。 查詢應該查看每個 id 的 number_col 中的最大值。 由於在我的示例中 4 是 id 1 的最大 number_col 值,因此它不應返回 1, 5 丟失。
如果您需要缺失值的范圍,則:
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
你可以使用這個查詢
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 具有 col_name > MIN(col_name)以丟棄第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.