-- replacing this with just returning the target count for simplicity 
-- can be simplified a lot more now as ignoring excludes...

select distinct
  targets.database_name,
  targets.database_id,
  target_cohorts.cohort_name as target_name,
  targets.target_id,
  targets.min_prior_observation,
  99999 as limit_to_first_in_n_days,
  NULL as nesting_cohort_id,
  NULL as nesting_name,
  NULL as min_age,
  NULL as max_age,	
  NULL as study_start,
  NULL as study_end,
  NULL as gender_concept_ids,
  outcome_cohorts.cohort_name as outcome_name,
  targets.outcome_id,
  targets.outcome_washout_days,
  targets.row_count as row_count,
  targets.person_count as person_count,
  targets.person_count as without_excluded_person_count
  
  from
  
  (select 
  d.CDM_SOURCE_ABBREVIATION as database_name,
  d.database_id,
  cc.target_cohort_ID as target_id,
  s2.outcome_cohort_id as outcome_id,
  cc.row_count,
  cc.person_count,
  cc.min_prior_observation,
  s2.outcome_washout_days

  from 
  @schema.@c_table_prefixcohort_counts cc
  inner join
  @schema.@database_table_name d
  on cc.database_id = d.database_id
  
  inner join
(
select distinct 
tcd.target_cohort_id,
tcd.outcome_cohort_id,
ts.outcome_washout_days

from
@schema.@c_table_prefixsettings ts
inner join
@schema.@c_table_prefixcohort_details tcd
on ts.setting_id = tcd.setting_id
and ts.database_id = tcd.database_id

where tcd.outcome_cohort_id != 0
{@use_characterization_target}?{ and tcd.target_cohort_id in (@characterization_target_id)}
{@use_outcome}?{ and tcd.outcome_cohort_id in (@outcome_id)}
{@use_outcome_washout}?{ and ts.outcome_washout_days in (@outcome_washout)}
) s2

on  
cc.target_cohort_id = s2.target_cohort_id

  where 
    cc.COHORT_TYPE in ('Target')
{@use_characterization_target}?{ and cc.TARGET_COHORT_ID in (@characterization_target_id)}
{@use_database}?{ and cc.database_id in (@database_id)}
    ) targets
    
  inner join @schema.@cg_table_prefixcohort_definition target_cohorts
    on target_cohorts.cohort_definition_id = targets.target_id
    
  left join @schema.@cg_table_prefixcohort_definition outcome_cohorts
    on outcome_cohorts.cohort_definition_id = targets.outcome_id
  
  ;