How to count number of non-consecutive values in a column using SQL?

我是研究僧i 提交于 2019-12-06 03:25:58

I would suggest using lag(). The idea is to count a "1", but only when the preceding value is zero or null:

select name, count(*)
from (select t.*,
             lag(srvc_inv) over (partition by name order by day) as prev_srvc_inv
      from t
     ) t
where (prev_srvc_inv is null or prev_srvc_inv = 0) and
      srvc_inv = 1
group by name;

You can simplify this a little by using a default value for lag():

select name, count(*)
from (select t.*,
             lag(srvc_inv, 1, 0) over (partition by name order by day) as prev_srvc_inv
      from t
     ) t
where prev_srvc_inv = 0 and srvc_inv = 1
group by name;

Something like this?

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>

You can try below query, having LAG function to handle the change in srvc_invl

select name, 1 any_invl, count(case when diff = 1 then 1 end) n_srvc_inv
from (select name, day, srvc_inv - LAG(srvc_inv, 1, 0) OVER(ORDER BY name, day) diff
      from tab
      order by name, day) temp
group by name

Here is the fiddle for your reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!