SELECT
  dm.cohort_definition_id,
  CAST(dm.table_concept_id AS BIGINT) * 1000 + dm.analysis_id AS covariate_id,
  c.concept_name                                                AS covariate_name,
  dm.table_concept_id                                           AS concept_id,
  dm.analysis_id,
  {@binary_mode} ? {COUNT(DISTINCT dm.subject_id)} : {COUNT(*)}  AS sum_value,
  {@binary_mode} ? {COUNT(DISTINCT dm.subject_id)} : {COUNT(*)} * 1.0 / stat.total_cnt AS mean_value
FROM #domain_raw_results dm
JOIN (
  SELECT cohort_definition_id, COUNT(DISTINCT subject_id) AS total_cnt
  FROM @cohort_database_schema.@cohort_table
  WHERE cohort_definition_id = @cohort_id
  GROUP BY cohort_definition_id
) stat
  ON dm.cohort_definition_id = stat.cohort_definition_id
JOIN @vocabulary_database_schema.concept c
  ON dm.table_concept_id = c.concept_id
WHERE dm.analysis_id = @analysis_id
GROUP BY
  dm.cohort_definition_id,
  dm.table_concept_id,
  c.concept_name,
  dm.analysis_id,
  stat.total_cnt
;
