-- noqa: disable=all
-- This sql was autogenerated as a reference example using the library
-- CLI. Its format is tied to the specific database it was run against,
-- and it may not be correct for all databases. Use the CLI's build 
-- option to derive the best SQL for your dataset.

-- ###########################################################


CREATE TABLE core__patient AS
WITH temp_patient AS (
    SELECT DISTINCT
        p.id,
        p.gender,
        p.address,
        cast(from_iso8601_timestamp(p.birthDate) AS date) AS birthDate,
        er.race_display,
        ee.ethnicity_display
    FROM
        patient AS p
    LEFT JOIN core__patient_ext_race AS er ON p.id = er.id
    LEFT JOIN core__patient_ext_ethnicity AS ee ON p.id = ee.id
),

-- Grab a single address to use for this patient, if present
temp_address AS (
    SELECT
        tp.id,
        
        
        
        substr(max(t_address.addr_row.postalcode), 1, 3) AS postalcode3
    FROM
        temp_patient AS tp,
        unnest(tp.address) AS t_address (addr_row)
    GROUP BY tp.id
)

SELECT DISTINCT
    tp.id,
    tp.gender,
    tp.birthDate,
    coalesce(ta.postalcode3, 'cumulus__none') AS postalCode_3,
    concat('Patient/', tp.id) AS subject_ref,
    coalesce(tp.race_display, 'unknown') AS race_display,
    coalesce(tp.ethnicity_display, 'unknown') AS ethnicity_display
FROM
    temp_patient AS tp
LEFT JOIN temp_address AS ta ON tp.id = ta.id

WHERE
    tp.birthDate IS NOT NULL
    AND tp.gender IS NOT NULL;
