【问题标题】:How to get the min value from the missing ordred values in a column in MySQL? [duplicate]如何从 MySQL 列中缺失的有序值中获取最小值? [复制]
【发布时间】:2016-07-16 09:22:12
【问题描述】:

我在 [1,2,3,4,6,7,9,11,12] 列中有以下整数值,我想编写一个查询,给出在这种情况下应该是 5 的最小正缺失整数

谢谢

【问题讨论】:

标签: mysql sql


【解决方案1】:

这是一种方法:

select min(t.col) + 1
from t
where not exists (select 1 from t t2 where t2.col = t.col + 1);

编辑:

如果我假设如果序列中缺少“1”,那么您想要“1”,那么:

select (case when max(tm.mincol) > 1 then 1
             else min(t.col) + 1
        end) as first_missing
from t cross join
     (select min(col) as mincol, max(col) as maxcol
      from t
     ) tm
where not exists (select 1 from t t2 where t2.col = t.col + 1);

【讨论】:

  • select (当 max(tm.REF) > 1 then 1 else min(gbs_don.REF) + 1 end) as first_missing from gbs_don cross join (select min(REF) as mincol, max( REF) as maxcol from gbs_don ) tm where not exists (select 1 from gbs_don t2 where t2.REF = t.REF + 1);
  • 在我的 SQL 查询上方出现错误:未知列 tm.REF
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 2013-09-20
  • 2019-12-28
  • 1970-01-01
相关资源
最近更新 更多