{% macro first_biopsy_cohort(events, grades, recruitment) %} with timeline as ( select * from {{ ref(events) }} where date <= {{ as_of() }} ), indexed as ( select person_id, min(date) as index_date from timeline where type = 'biopsy' and value_code in {{ sql_list(grades) }} group by person_id ), birth as ( select distinct person_id from timeline where type = 'birth' ), death as ( select person_id, min(date) as date from timeline where type = 'death' group by person_id ) select i.person_id, i.index_date, case when b.person_id is null then 'no_birth_date' when d.date <= i.index_date then 'died_by_index' end as excluded_by from indexed as i left join birth as b on b.person_id = i.person_id left join death as d on d.person_id = i.person_id where i.index_date >= '{{ recruitment[0] }}' and i.index_date < '{{ recruitment[1] }}' {% endmacro %}