SQLite Forum

How to convert to CTE
Login
> In the first query, you essentially ask in the inner query to first give you a list of all the records, except the records where the status is "Deceased". Once you have that list, Group by id (which does nothing other than allow a HAVING clause) and then using the having clause only give the records where the status is "Registered".

This is incorrect.

The inner mostest query returns a list of all id's which are 'Deceased' ever, for exclusion from any further processing.  Only records for id's where 'Deceased' is NEVER recorded throughout all eternity are candidates for further processing.

This set of candidate rows is further culled by the requirement that the date_status_added is less than the given constraint.

The remaining candidate rows are "grouped" by id (which is not unique and cannot be unique) and the row containing the max(date_status_added) is found -- this does not consider the reg_status (which could be 'Unregistered', 'Pregnant', or 'SARS-CoV-2 Infected', but will not be 'Deceased' at any time in its history).  

Amongst the candidates (peer group) having that id (group by) *and* the found max value, one of those rows must have a reg_status of 'Registered'.  Groups which do not meet this condition are skipped (they are removed as candidates).

Then, the number of id so found are counted.  What exactly this is supposed to represent I have no clue.  It most certainly is not the number of 'Registered' patients (but not yet dead) patients on the specified day.


The second query returns the count of the number of records where the date is less than a specified date and the reg_status is 'Registered'.

There is no "sameness" between the two queries except by happenstance.


Since we have no description of what it is that the OP is trying to obtain it will be impossible to provide any "how" to get it.