SQLite Forum

How to convert to CTE
Login
Also note that you need to push the final accumulation into the CTE if you want a partial date range in order to prevent the date constraint being pushed into the cumulative tally calculations.

```
with reg1(id, date, status, pstatus)
  as (
          select id,
                 date_status_added,
                 reg_status,
                 lag(reg_status, 1) over (partition by id order by date_status_added, reg_status desc)
            from reg_history_all
           where reg_status in ('Registered', 'Left', 'Deceased')
        order by id, date_status_added, reg_status desc
     ),
     reg2(id, date, cnt)
  as (
        select id,
               date,
               case when status == 'Registered' then 1
                    else case when pstatus == 'Registered' then -1
                              else 0
                          end
                end
          from reg1
         where status IS NOT pstatus
     ),
     reg3(date, cnt)
  as (
          select date,
                 sum(cnt)
            from reg2
        group by date
        order by date
     ),
     reg4(date, cnt)
  as (
        select date,
               sum(cnt) over (rows between unbounded preceding and current row)
          from reg3
      order by date
     )
select date,
       cnt
  from reg4
 where date between 4500 and 4600
;
```