1

可能重复:
如何在 SQL 中的组内按顺序查找缺失值?

我有像这样的值的列

MAC00006300
MAC00006301
MAC00006302
MAC00006305
.....
LED00006002
...........
LED00006008
ALD18965
ALD18967
ALD18968
.......
ALD19000

我需要值之间的缺失

MAC00006303,MAC00006304 
LET00006003 ..... LET00006007
ALD18969,ALD18970.....ALD18989

SELECT NAME, VALUE + 1
FROM testmissingexampledata  mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    testmissingexampledata mi 
        WHERE   mi.VALUE = mo.VALUE + 1
        )
ORDER BY
        VALUE;

当我执行上述查询时,我只能检索下一条丢失的记录。有人可以向我建议如何检索所有丢失的记录吗?

4

1 回答 1

1

如果没有要针对的所有可能数值的列表,您将无法返回丢失的行LEFT JOIN

这个查询(感觉它可能会更好/更强/更快,但它有效)会找到你的差距:

set @last_prefix = null;
set @last_value = null;
select result from (
    select @last_prefix, @last_value, name,
      @prefix := substring(name,1,3) as prefix,
      @value := substring(name,4) as value,
      case when @prefix = @last_prefix and @value != @last_value +1
        then concat ("gap from ", @prefix, ": ", @last_value+1, " to ", @value-1)
        else "ok" end as result,
      @last_prefix := @prefix, @last_value := @value
      from t20120921
) foo
where result != "ok";
于 2012-09-21T16:42:49.290 回答