Search code examples
sql-servergreatest-n-per-groupgaps-and-islands

how to delete repeated successive rows SQL


i have history table with many rows T1, i need information from 3 rows so i have new table T2, and i want copy this information from T1 to T2. but i have duplicate data ,so how copy right ? some duplicate rows i need and some not .only if on column D i have same data like rows before i don't need info from this row example: i have table looks like this - T1:

Id B D

1 8 10

2 8 3

3 8 3

4 8 10

i need this rows only - T2:

Id B D

1 8 10

2 8 3

4 8 10


Solution

  • Just compare with the previous row data, if match then do not include it by where condition

    ;WITH data AS
    (
        SELECT *, ROW_NUMBER() OVER (ORDER BY Id) AS Sequence FROM [Table]
    )
    SELECT Id, B, D 
    FROM data d 
    WHERE 
        NOT EXISTS
        (
            SELECT * 
            FROM data 
            WHERE Sequence + 1 = d.Sequence 
                AND B = d.B 
                AND D = d.D
        )