SELECT
  @cohort_id                                                      AS cohort_definition_id,
  CAST(@feature_cohort_id AS BIGINT) * 1000 + @analysis_id       AS covariate_id,
  '@feature_cohort_name'                                          AS covariate_name,
  @feature_cohort_id                                              AS concept_id,
  @analysis_id                                                    AS analysis_id,
  COUNT(DISTINCT cohort.subject_id)                               AS sum_value,
  COUNT(DISTINCT cohort.subject_id) * 1.0 / stat.total_cnt       AS mean_value
FROM @cohort_database_schema.@cohort_table cohort
INNER JOIN @table_database_schema.@table fc
  ON cohort.subject_id = fc.subject_id
JOIN (
  SELECT COUNT(DISTINCT subject_id) AS total_cnt
  FROM @cohort_database_schema.@cohort_table
  WHERE cohort_definition_id = @cohort_id
) stat
  ON 1 = 1
WHERE cohort.cohort_definition_id = @cohort_id
  AND fc.cohort_definition_id = @feature_cohort_id
{!@overlap_clause} ? {
  AND fc.@date_col >= DATEADD(DAY, @start_day, cohort.cohort_start_date)
  AND fc.@date_col <= DATEADD(DAY, @end_day, cohort.cohort_start_date)
} : {
  AND (
    fc.@date_col <= DATEADD(DAY, @end_day, cohort.cohort_start_date)
    AND fc.@date_end_col >= DATEADD(DAY, @start_day, cohort.cohort_start_date)
  )
}
GROUP BY stat.total_cnt
;
