Oracle
 sql >> Datenbank >  >> RDS >> Oracle

Wie zähle ich die Anzahl nicht aufeinanderfolgender Werte in einer Spalte mit SQL?

So etwas?

SQL> with test (name, day, srvc_inv) as
  2    (select 'bill', 1, 1 from dual union all
  3     select 'bill', 2, 1 from dual union all
  4     select 'bill', 3, 0 from dual union all
  5     select 'bill', 4, 0 from dual union all
  6     select 'bill', 5, 1 from dual union all
  7     select 'bill', 6, 0 from dual union all
  8     select 'susy', 1, 1 from dual union all
  9     select 'susy', 2, 0 from dual union all
 10     select 'susy', 3, 1 from dual union all
 11     select 'susy', 4, 0 from dual union all
 12     select 'susy', 5, 1 from dual
 13    ),
 14  inter as
 15    (select name, day, srvc_inv,
 16       nvl(lead(srvc_inv) over (partition by name order by day), 0) lsrvc
 17     from test
 18    )
 19  select name,
 20    sum(case when srvc_inv <> lsrvc and lsrvc = 0 then 1
 21             else 0
 22        end) grp
 23  from inter
 24  group by name;

NAME        GRP
---- ----------
bill          2
susy          3

SQL>