SQLite Forum

How to convert to CTE
Login
This is getting a lot closer:

WITH latest_registrations(added_date, ID) AS(
 SELECT MAX(A.rowid), ID
 FROM reg_history_all A
 WHERE A.REG_STATUS = 'Registered'
 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 100 UNION ALL SELECT day_date + 1 FROM all_dates WHERE day_date < 44300
), cumulative_registrations(day_date, cnt) 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(cnt,0) AS cnt
 FROM cumulative_registrations

I noticed counts seem only to go up by date, but that can't be right as the number of registered patients can go down (and do go down) as patients die or leave.

RBS