SQLite Forum

How to convert to CTE
Login
This next version works if you need the latest of the registrations per ID only, but for any type of registration - which seems implied in some previous posts:

```
WITH latest_registrations(added_date, ID) AS (
    SELECT MAX(A.DATE_STATUS_ADDED), ID
      FROM reg_history A
     WHERE A.REG_STATUS = 'Registered' AND NOT EXISTS(SELECT 1 FROM reg_history B WHERE B.ID = A.ID AND B.REG_STATUS = 'Deceased')
     GROUP BY A.ID
     ORDER BY 2,1
), non_deceased_registrations(added_date, added_count) AS (
    SELECT added_date, COUNT(*)
      FROM latest_registrations
     GROUP BY added_date
     ORDER BY added_date
), all_dates(day_date) AS (
    SELECT 10000 UNION ALL SELECT day_date+1 FROM all_dates WHERE day_date<44300
), cumulative_registrations(day_date, added_total_to_date) AS (
    SELECT day_date, SUM(added_count) OVER (ORDER BY day_date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
      FROM all_dates
      LEFT JOIN non_deceased_registrations ON added_date = day_date
)
SELECT day_date, COALESCE(added_total_to_date,0) AS added_total_to_date
  FROM cumulative_registrations
```

and this version works if you want the registration of specifically "Notification of registration" type registrations:

```
WITH non_deceased_registrations(added_date, added_count) AS (
    SELECT A.DATE_STATUS_ADDED, COUNT(*)
      FROM reg_history A
     WHERE A.REG_STATUS = 'Registered' AND A.LINKS_REG_STATUS = 'Notification of registration'
       AND NOT EXISTS(SELECT 1 FROM reg_history B WHERE B.ID = A.ID AND B.REG_STATUS = 'Deceased')
     GROUP BY A.DATE_STATUS_ADDED
     ORDER BY A.DATE_STATUS_ADDED
), all_dates(day_date) AS (
    SELECT 10000 UNION ALL SELECT day_date+1 FROM all_dates WHERE day_date<44300
), cumulative_registrations(day_date, added_total_to_date) AS (
    SELECT day_date, SUM(added_count) OVER (ORDER BY day_date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
      FROM all_dates
      LEFT JOIN non_deceased_registrations ON added_date = day_date
)
SELECT day_date, COALESCE(added_total_to_date,0) AS added_total_to_date
  FROM cumulative_registrations
```