2

Having a table with a column that represents a enumeration:

CASE 1

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

I need to get the max value in sequential order, in this case: '002'

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

Result expected: '029'.

CASE 2 But if the data is like this:

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

I need to get '004'.

Erick Asto Oblitas
  • 1,399
  • 3
  • 21
  • 47

3 Answers3

1

You need the first time that a gap is not one. Assuming the values are actually numbers, the easiest way is to use 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;

EDIT:

In SQL Server 2008, you can do the same thing with 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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Something like this should work:

;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)
;
RBarryYoung
  • 55,398
  • 14
  • 96
  • 137
-1

There is no need for windowed function/cte/subqueries. You can use simple 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

You need to find first record that does not have consecutive record. Using self outer join and where you will get records that don't have consecutive records and MIN to get first of them.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • **For funny downvoter, leave a comment why this code is bad** – Lukasz Szozda Nov 30 '15 at 17:01
  • not the down voter but if you try your solution with `INSERT INTO #tab VALUES ('001'),('002'),('003'),('005'),('006')` , it should return `004` but it doesnt :) – M.Ali Nov 30 '15 at 17:08
  • @M.Ali It should return `003`. It is the first gap - 1. Max sequential value starting from beginning. Check OP examples. Am I right? – Lukasz Szozda Nov 30 '15 at 17:09
  • read my comment again, if you insert the value `003` in the table it will still return `003` I think. – M.Ali Nov 30 '15 at 17:13
  • @M.Ali I run your [example](https://data.stackexchange.com/stackoverflow/query/401179) and it return `003` why is it wrong? OP doesn't want first gap which is 004. Check first OP example `('001', '002', '005', '006')` => `'002'` not `'003'` – Lukasz Szozda Nov 30 '15 at 17:13