Files
ISSSTELEON/Persistance/dbt/models/gold/cacu/cacu_procedures.sql
T

76 lines
3.1 KiB
SQL

{#
One row per colposcopy day and per biopsy of a patient, with the cytology that led to it and
the histology that answers it.
- The cytology: the one the biopsy's record names (`link` recorded), else her latest valid
one reported before the procedure, at most CYTOLOGY_BEFORE_DAYS before (inferred).
- A colposcopy's histology: the most severe reported of the biopsies requested from that day
and within the colposcopy_to_biopsy horizon.
cacu_events also dates a colposcopy at the report of a biopsy taken at it: not a day of one.
#}
{% set p = var('cacu') %}
with biopsy as (
select
person_id, request_date as date, cytology_sample_date as recorded, report_date, histology,
known_at, report_known_at,
case
{%- for grade in p.biopsy_severity %}
when histology = '{{ grade }}' then {{ loop.index }}
{%- endfor %}
else 0
end as severity
from {{ ref('cervical_biopsy') }}
),
colposcopy as (
select person_id, date, min(known_at) as known_at
from {{ ref('cacu_events') }}
where type = 'colposcopy'
and not (source_table = 'cervical_biopsy' and source_id <> cast(date as {{ dbt.type_string() }}))
group by person_id, date
),
answered as (
select
c.person_id, c.date, b.report_date, b.histology, b.report_known_at,
row_number() over (partition by c.person_id, c.date
order by b.severity desc, b.report_date, b.date) as n
from colposcopy as c
join biopsy as b on b.person_id = c.person_id and b.date >= c.date
where b.histology is not null and b.report_date is not null
and {{ days_between('c.date', 'b.date') }} <= {{ p.horizons.colposcopy_to_biopsy }}
),
procedures as (
select 'biopsy' as type, person_id, date, recorded, report_date, histology,
known_at, report_known_at
from biopsy
union all
select 'colposcopy', c.person_id, c.date, null, a.report_date, a.histology,
c.known_at, a.report_known_at
from colposcopy as c
left join answered as a on a.person_id = c.person_id and a.date = c.date and a.n = 1
),
referred as (
select
x.type, x.person_id, x.date, c.sample_date,
row_number() over (partition by x.type, x.person_id, x.date
order by c.sample_date desc, c.report_date desc) as n
from procedures as x
join {{ ref('cervical_cytology') }} as c on c.person_id = x.person_id
where {{ cacu_valid_cytology('c') }}
and c.sample_date < x.date and c.report_date < x.date
and {{ days_between('c.report_date', 'x.date') }} <= {{ p.cytology_before_days }}
)
select
{{ dbt.concat(['x.person_id', "'|'", 'cast(x.date as ' ~ dbt.type_string() ~ ')']) }} as procedure_id,
x.type, x.person_id, x.date,
coalesce(x.recorded, r.sample_date) as sample_date,
case when x.recorded is not null then 'recorded'
when r.sample_date is not null then 'inferred' end as link,
x.report_date, x.histology, x.known_at, x.report_known_at
from procedures as x
left join referred as r
on r.type = x.type and r.person_id = x.person_id and r.date = x.date and r.n = 1