计算连续零及其实例的数量 SQL

Count the number of consecutive Zeros along with their instances SQL

数据如下:

Row_No    ID     Bal
1        01      0
2        01      0
3        01      0
4        01      10
5        01      0
6        01      0
7        01      20
8        01      0
9        02      30
10       02      0
11       02      40
12       02      10
13       02      0
14       02      25
15       02      0
16       02      0
17       02      0

实例 = 连续零的次数

计数(consecutive_zeros) = 总零

ID = 01:

实例:

第 1 个实例: Row_No 1,2,3

第 2 个实例: Row_No 5,6

计数(consecutive_zeros):

例如没有 1 我们有 3 个零

例如没有 2 w 有 2 个零

总计 = 5

Row_no 8 不被考虑,因为它后面没有连续的零

需要输出

ID    instances    count(consecutive_zeros)
01    2            5 
02    1            3

;为此,您可以使用 lag()lead():

select id,
       sum(case when bal = 0 and (prev_bal = 0 or prev_bal is null) and
                     next_bal = 0
                then 1 else 0
            end) as instances,
       sum(case when bal = 0 and prev_bal = 0 then 1 else 0 end)
from (select t.*,
             lag(bal) over (partition by id order by row_no) as prev_bal,
             lead(bal) over (partition by id order by row_no) as next_bal
      from t
     ) t
group by id;

您不必将其视为间隙和孤岛问题。你的两个措施很简单:

  • instances 在值“更改”为 0 并且下一个值也是 0 时计数。
  • count 计算值为 0 且下一个值为 0 的值。

戈丁·利诺夫,您的回答近乎完美。但是,这将给出准确的结果:

select  id
        ,BAL_CON_ZERO_INSTANCES+ (total_zeros-BAL_CON_ZERO_DAYS) AS BAL_CON_ZERO_INSTANCES
        ,BAL_CON_ZERO_DAYS
(
select id,

        ,sum(case when bal = 0 and (prev_bal = 0 or prev_bal is null) and (next_bal = 1 or next_bal is null) 
                then 1 else 0
            end)  as BAL_CON_ZERO_INSTANCES
        ,sum(case when (bal = 0 and (next_bal = 0 or next_bal is null) or (bal = 0 and (prev_bal = 0 or prev_bal is null) and (next_bal = 1 or next_bal is null))) then 1 else 0 end) as BAL_CON_ZERO_DAYS
        ,sum(case when bal = 0 then 1 else 0 end) as total_zeros

from (select t.*,
             bal,
             lag(bal) over (partition by id order by row_no) as prev_bal,
             lead(bal) over (partition by id order by row_no) as next_bal
      from t
     ) t
group by id;