Files
ISSSTELEON/Transformation/macros/primer_evento_posterior.sql
T
edgar 4a04f411c0 feat(cacu): add the times from sample and from diagnosis to treatment
A macro finds the first event of a kind after each start, for the same patient, within a horizon. The diagnosis
lookup of cacu_tomas_citologia uses it with the same result, and two more calls give the days from the sample to
the first treatment and from its diagnosis to it. Both horizons are 60 days, provisional.
2026-11-22 00:23:42 -06:00

31 lines
1.7 KiB
SQL

{#
The first event of a kind after each start, for the same patient: the building block of a time between two events.
`inicio`: a relation with one row per start, with columns `id`, `pac_id` and the date `fecha`.
`linea`: the patient's timeline (`pac_id`, `fecha`, `conocida_en`, `tipo`).
`tipo`: the timeline kind that ends the interval.
`horizonte_dias`: the event must fall fewer days after the start.
`estricto`: true leaves out an event on the start's own day, false counts it.
One row per start that has such an event: `inicio_id`, `fecha_fin` (its date) and `fin_conocido_en` (when it became
known: the earliest load among the patient's events of that day). The days between are the difference of
`dim_fecha.dia_num`, plain arithmetic that every engine runs. The caller joins on `inicio_id`; a start without a
row has no event in its horizon.
#}
{% macro primer_evento_posterior(inicio, id, fecha, linea, tipo, horizonte_dias, estricto=true) -%}
select p.inicio_id, p.fecha_fin, min(l.conocida_en) as fin_conocido_en
from (
select i.{{ id }} as inicio_id, min(l.fecha) as fecha_fin
from {{ inicio }} i
join {{ linea }} l
on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha {{ '>' if estricto else '>=' }} i.{{ fecha }}
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} di on di.fecha = i.{{ fecha }}
where dl.dia_num - di.dia_num < {{ horizonte_dias }}
group by i.{{ id }}
) p
join {{ inicio }} i on i.{{ id }} = p.inicio_id
join {{ linea }} l on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha = p.fecha_fin
group by p.inicio_id, p.fecha_fin
{%- endmacro %}