如何获得最大连续值?

时间:2015-11-30 16:32:25

标签: sql sql-server sql-server-2008 tsql enumeration

使用包含表示枚举的列的表:

案例1

| CustomID | Values |
|     '001'|     ...|
|     '002'|     ...|
|     '005'|     ...|
|     '006'|     ...|

我需要按顺序获取最大值,在这种情况下:'002'

| CustomID | Values |
|     '028'|     ...|
|     '029'|     ...|
|     '031'|     ...|
|     '032'|     ...|

预期结果:'029'

案例2 但如果数据是这样的:

| CustomID | Values |
|     '001'|     ...|
|     '002'|     ...|
|     '003'|     ...|
|     '004'|     ...|

我需要'004'

3 个答案:

答案 0 :(得分:1)

你需要第一次差距不是一个。假设这些值实际上是数字,最简单的方法是使用lead()

select min(t.customId)
from (select t.*,
             lead(customId) over (order by CustomId) as next_customId
      from t
     ) t
where next_CustomId is null or next_CustomId <> CustomId + 1;

编辑:

在SQL Server 2008中,您可以使用outer apply执行相同操作:

select min(t.customId)
from (select t.*,
             next.customId as next_customId
      from t outer apply
           (select top 1 t2.*
            from t t2
            where t2.CustomId > t.CustomId
            order by t2.CustomId
           ) next
     ) t
where next_CustomId is null or next_CustomId <> CustomId + 1;

答案 1 :(得分:0)

这样的事情应该有效:

;WITH cte As
(
    SELECT CAST(CustomID As INT) As cid FROM yourTable
)
SELECT MIN(cid) As MaxSeq
FROM   cte As c1
WHERE  NOT EXISTS(Select * From cte As c2 Where c2.cid = c1.cid+1)
;

答案 2 :(得分:-1)

不需要窗口函数/ cte /子查询。您可以使用简单的LEFT JOIN

SELECT MIN(t.CustomID)
FROM #tab t
LEFT JOIN #tab t1
  ON t.CustomID = t1.CustomID - 1
WHERE t1.CustomID IS NULL;

LiveDemo

您需要查找没有连续记录的第一条记录。使用自我外部联接,您将获得没有连续记录的记录,并MIN获取第一个记录。