-- 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__medication AS (
    WITH
    
    mcc_nonnull AS (
        SELECT 
            id,
            encounter, 
            subject, 
            medicationcodeableconcept 
        FROM medicationrequest 
        WHERE medicationcodeableconcept IS NOT NULL
        AND encounter IS NOT NULL
    ),
    inline_medication AS (
        SELECT
            id,
            subject.reference as patient_ref,
            encounter.reference AS encounter_ref,
            t.r.code,
            t.r.display,
            t.r.system AS code_system,
            
            false AS userselected
            
        FROM mcc_nonnull,
        unnest(medicationcodeableconcept.coding) AS t(r)
    )
    
    
    
    SELECT
        id,
        encounter_ref,
        patient_ref,
        code,
        display,
        code_system,
        userselected
    FROM
        inline_medication
);
