Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement