SQLite Forum

How to convert to CTE
Login
For example.  If the data that you want is defined as:

For the table reg_history_all with the fields id, date_status_added, and reg_status then for each date in the range of min(date_status_added) to max(date_status_added) calculate the number of unique id that have reg_status = 'Registered' on or before that date less the number of unique id that have reg_status = 'Deceased' on or before that date.

That is, calculate the number of "active id" for each date where "active" is defined as "Registered" on or before the date and not "Deceased" on or before that date, where each "id" is always "Registered" before it becomes "Deceased".

You can translate that into SQL directly.

```
with date_range(date) -- the dates we are interested in
  as (
         select min(date_status_added)
           from reg_history_all
      union all
         select date + 1
           from date_range
          where date < (
                        select max(date_status_added)
                          from reg_history_all
                       )
     )
select date,
       (
        select count(distinct id)
          from reg_history_all
         where date_status_added <= date
           and reg_status == 'Registered'
       )
       -
       (
        select count(distinct id)
          from reg_history_all
         where date_status_all <= date
           and reg_status == 'Deceased'
       )
  from date_range
;
```

There may be other (more efficient) ways to compute this depending on the quality of the source data (additional constraints).