Files
ISSSTELEON/Persistance/dbt/models/silver/observation.sql
T
alberto 781e1ea75a C1a: code only, no comments, no Markdown
The four Markdown files (README.md, tests/fixtures/ados2_items_by_module.md, tools/delivery/README.md, tools/delivery/README.repo.md) live in the outer repo under docs/ISSSTELEON; the delivery scripts no longer produce a README and the ADOS-2 expected values stay in the Python test.
2026-12-01 16:56:14 -06:00

67 lines
2.3 KiB
SQL

{%- if not staged_exists('staged__observation') %}
select
cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as {{ dbt.type_string() }}) as study,
cast(null as {{ dbt.type_string() }}) as instance,
cast(null as {{ dbt.type_string() }}) as field,
cast(null as {{ dbt.type_string() }}) as value_text,
cast(null as {{ dbt.type_float() }}) as value_num,
cast(null as {{ dbt.type_boolean() }}) as value_bool,
cast(null as date) as value_date,
cast(null as {{ dbt.type_timestamp() }}) as known_at,
0 as rows_merged
where 1 = 0
{%- else %}
with accepted as (
select * from {{ source('bronze', 'staged__observation') }} as s
where s.person_id is not null
{%- if staged_exists('review_log') %}
and not exists (
select 1 from {{ source('bronze', 'review_log') }} as r
where r.entity = s.study and r._record = s._record
)
{%- endif %}
),
cells as (
select
person_id, study, instance, field,
max(value_text) as value_text, count(distinct value_text) as n_text,
max(value_num) as value_num, count(distinct value_num) as n_num,
max(value_date) as value_date, count(distinct value_date) as n_date,
max(case when value_bool then 1 else 0 end) as bool_any,
min(case when value_bool then 1 else 0 end) as bool_all,
count(value_bool) as n_bool
from accepted
group by person_id, study, instance, field
),
instances as (
select
person_id, study, instance,
min(known_at) as known_at,
count(distinct {{ dbt.concat(['_record', "':'", 'cast(_index as ' ~ dbt.type_string() ~ ')']) }}) as rows_merged
from accepted
group by person_id, study, instance
),
conflicted as (
select distinct person_id, study, instance from cells
where n_text > 1 or n_num > 1 or n_date > 1 or (n_bool > 0 and bool_any <> bool_all)
)
select
c.person_id, c.study, c.instance, c.field,
c.value_text, c.value_num,
case when c.n_bool = 0 then null else c.bool_any = 1 end as value_bool,
c.value_date,
i.known_at, i.rows_merged
from cells as c
join instances as i
on i.person_id = c.person_id and i.study = c.study and i.instance = c.instance
where not exists (
select 1 from conflicted as x
where x.person_id = c.person_id and x.study = c.study and x.instance = c.instance
)
{%- endif %}