How to count consecutive duplicates in a table?

前端 未结 6 2042
闹比i
闹比i 2021-01-13 09:52

I have below question:
Want to find the consecutive duplicates

SLNO   NAME     PG   
1       A1      NO                   
2       A2      YES                    


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 10:21

    SELECT MAX(consecutives) -- Block 1
    FROM (
        SELECT t1.pg, t1.slno, COUNT(*) AS consecutives -- Block 2
        FROM test t1 INNER JOIN test t2 ON t1.pg = t2.pg
        WHERE t1.slno <= t2.slno
          AND NOT EXISTS (
            SELECT *  -- Block 3
            FROM test t3 
            WHERE t3.slno > t1.slno
              AND t3.slno < t2.slno
              AND t3.pg  != t1.pg
        )    
        GROUP BY t1.pg, t1.slno
    );
    

    The query calculates the result in following way:

    • Extract all couples of records that don't have a record with different value of PG in between (blocks 2 and 3)
    • Group them by PG value and starting SLNO value -> this counts the consecutive values for any [PG, (starting) SLNO] couple (block 2);
    • Extract Maximum value from query 2 (block 1)

    Note that the query may be simplified if the slno field in table contains consecutive values, but this seems not your case (in your example record with SLNO = 5 is missing)

提交回复
热议问题