How to count consecutive duplicates in a table?

前端 未结 6 1950
闹比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条回答
  •  礼貌的吻别
    2021-01-13 10:18

    with test as (
    select 1 slno,'A1' name ,'NO' pg from dual union all 
    select 2,'A2','YES' from dual union all
    select 3,'A3','NO' from dual union all
    select 4,'A4','YES' from dual union all
    select 6,'A5','YES' from dual union all
    select 7,'A6','YES' from dual union all
    select 8,'A7','YES' from dual union all
    select 9,'A8','YES' from dual union all
    select 10,'A9','YES' from dual union all
    select 11,'A10','NO' from dual union all
    select 12,'A11','YES' from dual union all
    select 13,'A12','NO' from dual union all
    select 14,'A14','NO' from dual),
    consecutive as (select row_number() over(order by slno) rr, x.* 
                  from test x)
    select x.* from Consecutive x
      left join Consecutive y on x.rr = y.rr+1 and x.pg = y.pg
      where y.rr is not null
      order by x.slno 
    

    And you can control output with condition in where.

    where y.rr is not null query returns duplicates

    where y.rr is null query returns "distinct" values.

提交回复
热议问题