     else e.cohort_end_date
   end cohort_end_date
 FROM
-  (SELECT
-    event.id,
+  (SELECT DISTINCT
     event.event_cohort_index,
     event.subject_id,
     COALESCE(start_dr.replacement_date, event.cohort_start_date) cohort_start_date,

* SELECT 1 AS cohort_definition_id, 1 AS cohort_index UNION ALL ...
*/

select id, event_cohort_index, subject_id, CAST(cohort_start_date AS DATETIME) AS cohort_start_date, CAST(cohort_end_date AS DATETIME) AS cohort_end_date
INTO #raw_events
FROM (
	SELECT ROW_NUMBER() OVER (ORDER BY e.cohort_start_date) AS id,
	  ec.cohort_index AS event_cohort_index,
	  e.subject_id,
	  e.cohort_start_date,
	  dateadd(d, 1, e.cohort_end_date) as cohort_end_date

*/

SELECT
  ROW_NUMBER() OVER (ORDER BY e.cohort_start_date) AS id,
  e.event_cohort_index,
  e.subject_id,
  e.cohort_start_date,
