-- 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.

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



-- This table includes all fields of interest to the US Core Specimen profile.
-- BUT ADDING:
-- * the `status` field, because it seems useful
--
-- US Core profile for reference:
-- * http://hl7.org/fhir/us/core/STU6.1/StructureDefinition-us-core-specimen.html

CREATE TABLE core__specimen AS
WITH temp_specimen AS (
    SELECT
        src.id,
        src.status,
        src.subject.reference AS subject_ref
    FROM specimen AS src
    WHERE (src.status IS NULL OR src.status <> 'entered-in-error')
)

SELECT
    src.id,
    src.status,

    dn_type.code AS type_code,
    dn_type.system AS type_system,
    dn_type.display AS type_display,

    concat('Specimen/', src.id) AS specimen_ref,
    src.subject_ref

FROM temp_specimen AS src
LEFT JOIN core__specimen_dn_type AS dn_type ON src.id = dn_type.id;
