Oracle
 sql >> Database >  >> RDS >> Oracle

Come contare i duplicati consecutivi in ​​una tabella?

Si può fare con il metodo Tabibitosan. Esegui questo, per capirlo:

with a as(
select 1 slno, 'A' pg from dual union all
select 2 slno, 'A' pg from dual union all
select 3 slno, 'B' pg from dual union all
select 4 slno, 'A' pg from dual union all
select 5 slno, 'A' pg from dual union all
select 6 slno, 'A' pg from dual 
)
select slno, pg, newgrp, sum(newgrp) over (order by slno) grp
from( 
    select slno, 
           pg, 
           case when pg <> nvl(lag(pg) over (order by slno),1) then 1 else 0 end newgrp
    from a
    );

Newgrp significa che è stato trovato un nuovo gruppo.

Risultato:

SLNO PG NEWGRP GRP
1    A  1      1
2    A  0      1
3    B  1      2
4    A  1      3
5    A  0      3
6    A  0      3

Ora, usa semplicemente un gruppo per con conteggio, per trovare il gruppo con il numero massimo di occorrenze:

with a as(
select 1 slno, 'A' pg from dual union all
select 2 slno, 'A' pg from dual union all
select 3 slno, 'B' pg from dual union all
select 4 slno, 'A' pg from dual union all
select 5 slno, 'A' pg from dual union all
select 6 slno, 'A' pg from dual 
),
b as(
select slno, pg, newgrp, sum(newgrp) over (order by slno) grp
from( 
    select slno, pg, case when pg <> nvl(lag(pg) over (order by slno),1) then 1 else 0 end newgrp
    from a
    )
)
select max(cnt)
from (
    select grp, count(*) cnt
    from b
    group by grp
    );