sql >> Base de Datos >  >> RDS >> PostgreSQL

Cuente dónde cambia la columna a un valor específico en postgres

Usar lag para obtener el valor en la fila anterior y contar a partir de entonces según las condiciones.

select count(*)
from (select action_date,action,lag(action) over(order by action_date) as prev_action
      from t
     ) t
where (action<>prev_action and action=1) or (action=1 and prev_action is null)

O se puede simplificar como

select 
count(case when lag(action) over(order by action_date) is null then and action = 1 then 1
           when lag(action) over(order by action_date) is not null and lag(action) over(order by action_date) <> action and action = 1 then 1 
      end) as cnt
from t