根据当前行和先前行计算列更改值的次数

Count number of times a column has changed value based on current and previous rows

我有以下结果集。

Product  Date       Status    
123      1/1/2017   Active    
123      2/1/2017   Inactive  
123      3/1/2017   Active    
456      1/1/2017   Active    
456      1/2/2017   Active    
456      1/3/2017   Inactive  
789      1/7/2017   Active    
789      1/15/2017  Active    
789      1/21/2017  Active    
111      1/7/2017   Inactive 
111      1/15/2017  Active    
111      1/21/2017  Inactive  
111      1/23/2017  Active 
111      1/31/2017  Inactive

我想尝试确定产品更改状态的次数,但让每一行都显示截至该行日期的次数。或者,我也可以简单地显示每个产品的不同状态计数(也在给定日期)。

我想这将需要某种 window 函数对产品进行分区并按日期排序,但我还没有遇到任何运气。

所需的结果如下所示:

Product  Date       Status    # of Distinct Status  # of Status Change
123      1/1/2017   Active    1                     0
123      2/1/2017   Inactive  2                     1
123      3/1/2017   Active    2                     2 
456      1/1/2017   Active    1                     0
456      1/2/2017   Active    1                     0
456      1/3/2017   Inactive  2                     1
789      1/7/2017   Active    1                     0
789      1/15/2017  Active    1                     0
789      1/21/2017  Active    1                     0
111      1/7/2017   Inactive  1                     0
111      1/15/2017  Active    2                     1
111      1/21/2017  Inactive  2                     2
111      1/23/2017  Active    2                     3
111      1/31/2017  Inactive  2                     4

您可以使用 lagsum window 函数

select id,date,status,
sum(case when prev_status is null or prev_status=status then 0 else 1 end) over(partition by product order by date) as num_of_status_change
from (select id,date,status,lag(status) over(partition by product order by date) as prev_status
      from tbl
     ) t