How would I turn this SQL into a CTE where the Excel date (here 35100) goes from 8623 to 44310? select 35100 as last_date, count(*) as cnt from (select 1 from reg_history_all where rowid in(select last_rowid from( select id, max(rowid) as last_rowid from reg_history_all where date_status_added <= 35100 group by id having reg_status = 'Registered'))) RBS