CREATE TABLE IF NOT EXISTS #domain_raw_results (
  cohort_definition_id int,
  row_id int,
  subject_id int,
  table_concept_id int,
  cohort_start_date date,
  analysis_id int
);

INSERT INTO #domain_raw_results (
  cohort_definition_id,
  row_id,
  subject_id,
  table_concept_id,
  cohort_start_date,
  analysis_id
)
SELECT DISTINCT
  cohort.cohort_definition_id,
  cohort.@row_id_field AS row_id,
  cohort.subject_id,
  {@atc} ? {atc_ca.ancestor_concept_id} : {dt.@concept_id_col},
  cohort.cohort_start_date,
  @analysis_id AS analysis_id
FROM @cohort_database_schema.@cohort_table cohort
INNER JOIN @table_database_schema.@table dt
  ON cohort.subject_id = dt.@person_id_col
{@concept_set} ? {
  INNER JOIN #concept_sets_c cst
    ON cst.concept_id = dt.@concept_id_col
} : {}
{@atc} ? {
  INNER JOIN @vocabulary_database_schema.concept_ancestor atc_ca
    ON atc_ca.descendant_concept_id = dt.@concept_id_col
  INNER JOIN @vocabulary_database_schema.concept atc_anc
    ON atc_anc.concept_id = atc_ca.ancestor_concept_id
    AND atc_anc.vocabulary_id = 'ATC'
    AND atc_anc.concept_class_id = '@drug_atc_class'
    AND atc_anc.invalid_reason IS NULL
} : {}
WHERE cohort.cohort_definition_id = @cohort_id
  AND dt.@concept_id_col != 0
{!@overlap_clause} ? {
  AND dt.@date_col >= DATEADD(DAY, @start_day, cohort.cohort_start_date)
  AND dt.@date_col <= DATEADD(DAY, @end_day, cohort.cohort_start_date)
} : {
  AND (
    dt.@date_col <= DATEADD(DAY, @end_day, cohort.cohort_start_date)
  AND dt.@date_end_col >= DATEADD(DAY, @start_day, cohort.cohort_start_date)
  )
}
