歯抜けの最小値を探す

分析関数の衝撃(前編)ですでに答えは出ているのだけれど、同じ結果が抽出できるクエリを作ってしまったので、メモ。

select min(id + 1) as gap
from (
  select 0 as id
  union
  select id
  from tablename
) as dummy
where id + 1 not in (
  select id
  from tablename
);

MySQLで動作検証済み。

(1, 2, 3, 4, 5)のうち、(3)が抜けて(1, 2, 4, 5)となっている場合は、(3)が取得できる。

(1, 2, 3, 4, 5)のうち、(1)が抜けて(2, 3, 4, 5)となっている場合は、ちゃんと(1)が取得できる。

(1, 2, 3, 4, 5)のいずれも抜けがなければ、(6)が返却される。

ちなみに、(1, 2, 3, 4, 5)のいずれも抜けがない場合にnullを返却するようにしたい場合は、where節に” id + 1 <= 5″を追加する。

select min(id + 1) as gap
from (
  select 0 as id
  union
  select id
  from tablename
) as dummy
where id + 1 not in (
  select id
  from tablename
) and id + 1 <= 5;
投稿日:
カテゴリー: SQL

1件のコメント

コメントは受け付けていません。