简体   繁体   中英

SQL Server query to find where all preceding numbers are not included per each ID for a specific column

I am having a hard time trying to explain this succinctly but basically I need to query Table A for each ID number and find where in the positions column there are missing sequential numbers for each specific ID. If there is a position 7 for a certain ID, then there should be a 6, 5, 4, 3, 2, 1 position for that ID as well. Each ID can have anywhere from 1-15 position records.

Does anyone have any suggestions on the best way to go about this?

Edited to Add: There is only one ID column, it is called GlobalID. There is only one Positions column. The end result is that I will update an Issues column with a code specific to the problem, it will populate with PositionsIncorrect for each GlobalID record where there is an incorrect sequence of numbers in the Positions column.

If you just want to identify the gaps, you can use lead() in a subuqery to get the value of the next position for the same id , and then do comparison in the outer query:

select * 
from (
    select
        id,
        position,
        lead(position) over(partition by id order by position) lead_position
    from tableA
) x
where lead_position is not null and lead_position != position + 1

This will return one row for each record of the same id where the next record is not in sequence, along with the position of the next record.

Something like this will show which positions are missing:

DECLARE @t table
(
    ID int
    , Position int
)

INSERT INTO @t (ID, Position)
VALUES
(1, 4)
, (1, 15)
, (2, 3)
, (2, 10)
;

WITH cte
AS
(
    SELECT
        ID
        , MIN(Position) Position
        , MAX(Position) MaxPosition
    FROM @t
    GROUP BY ID

    UNION ALL

    SELECT
        ID
        , Position + 1
        , MaxPosition
    FROM cte
    WHERE Position + 1 <= MaxPosition
)

SELECT
    C.ID
    , C.Position
    , CAST(CASE WHEN T.ID IS NULL THEN 1 ELSE 0 END AS bit) Missing
FROM
    cte C
    LEFT JOIN @t T ON
        C.ID = T.ID
        AND C.Position = T.Position
ORDER BY
    ID
    , Position
OPTION (MAXRECURSION 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM