Skip to content
Advertisement

Get count of records changing status

I am trying to figure the best way to get a count of how many times a record was sent back to the user (Status changed from 3 or 4 back to 1)

this is what my data looks like

ID   record_id  status_id
1    10909      2           
2    10909      3
3    10909      1
4    10909      3
5    10909      3
6    10909      4
7    10909      5

Advertisement

Answer

SQL tables represent unordered sets. There is no “previous” or “next” row, unless a column specifies the ordering.

Your data does not seem to have such a column. But if you did, you could use lag():

select record_id, count(*)
from (select t.*,
             lag(status) over (partition by record_id order by <ordering column>) as prev_status
      from t
     ) t
where status = 1 and prev_status in (3, 4)
group by record_id;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement