SQL - Find missing int values in mostly ordered sequential series

前端 未结 6 628
有刺的猬
有刺的猬 2020-12-06 08:59

I manage a message based system in which a sequence of unique integer ids will be entirely represented at the end of the day, though they will not necessarily arrive in orde

6条回答
  •  Happy的楠姐
    2020-12-06 09:27

    I've been there.

    FOR ORACLE:

    I found this extremely useful query on the net a while ago and noted down, however I don't remember the site now, you may search for "GAP ANALYSIS" on Google.

    SELECT   CASE
                 WHEN ids + 1 = lead_no - 1 THEN TO_CHAR (ids +1)
              ELSE TO_CHAR (ids + 1) || '-' || TO_CHAR (lead_no - 1)
             END
                 Missing_track_no
       FROM   (SELECT   ids,
                        LEAD (ids, 1, NULL)
                         OVER (ORDER BY ids ASC)
                            lead_no
                 FROM   YOURTABLE
                 )
       WHERE   lead_no != ids + 1
    

    Here, the result is:

    MISSING _TRACK_NO
    -----------------
           6
    

    If there were multiple gaps,say 2,6,7,9 then it would be:

    MISSING _TRACK_NO
    -----------------
            2
           6-7
            9
    

提交回复
热议问题