R/m4_addMatView.R

Defines functions addMatView_4

Documented in addMatView_4

#' add materialized view data for mimic IV
#' @param range which to be added
#' @param conn connection of MIMIC, if missing, it well be got from global environment by connect_MIMIC
#'
#' @return 58 materialized view data
#' @export
#'
#' @examples
#' \donttest{
#' addMatView_4()
#' }
addMatView_4 <- function(range,conn){
# demographics 4 - 0

age <- "SET client_min_messages TO WARNING;\nset search_path to mimic4;\ndrop materialized view if exists demographics_age;\ncreate materialized view mimic4.demographics_age\ntablespace pg_default\nas\n-- jing add head\nSELECT \t\n\tad.subject_id\n\t, ad.hadm_id\n\t, ad.admittime\n\t, pa.anchor_age\n\t, pa.anchor_year\n\t, datetime_diff(ad.admittime, DATETIME(pa.anchor_year, 1, 1, 0, 0, 0), 'YEAR') + pa.anchor_age AS age\nFROM admissions ad\nINNER JOIN patients pa\nON ad.subject_id = pa.subject_id\n;\n-- jing add tail\nalter table mimic4.demographics_age\nowner to postgres;"
icustay_detail <- "SET client_min_messages TO WARNING;\nset search_path to mimic4;\ndrop materialized view if exists demographics_icustay_detail;\ncreate materialized view mimic4.demographics_icustay_detail\ntablespace pg_default\nas\n-- jing add head\nSELECT ie.subject_id, ie.hadm_id, ie.stay_id\n-- patient level factors\n, pat.gender, pat.dod\n-- hospital level factors\n, adm.admittime, adm.dischtime\n, datetime_diff(adm.dischtime, adm.admittime, 'DAY') as los_hospital\n, datetime_diff(adm.admittime, DATETIME(pat.anchor_year, 1, 1, 0, 0, 0), 'YEAR') + pat.anchor_age as admission_age\n, adm.ethnicity\n, adm.hospital_expire_flag\n, DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) AS hospstay_seq\n, CASE\n    WHEN DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) = 1 THEN True\n    ELSE False END AS first_hosp_stay\n-- icu level factors\n, ie.intime as icu_intime, ie.outtime as icu_outtime\n, ROUND(datetime_diff(ie.outtime, ie.intime, 'HOUR')/24.0, 2) as los_icu\n, DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) AS icustay_seq\n-- first ICU stay *for the current hospitalization*\n, CASE\n    WHEN DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) = 1 THEN True\n    ELSE False END AS first_icu_stay\nFROM icustays ie\nINNER JOIN admissions adm\n    ON ie.hadm_id = adm.hadm_id\nINNER JOIN patients pat\n    ON ie.subject_id = pat.subject_id;\n-- jing add tail\nalter table mimic4.demographics_icustay_detail\nowner to postgres;"
icustay_times <- "SET client_min_messages TO WARNING;\nset search_path to mimic4;\ndrop materialized view if exists demographics_icustay_times;\ncreate materialized view mimic4.demographics_icustay_times\ntablespace pg_default\nas\n-- jing add head\n-- involves first creating a lag/lead version of disch/admit time\n-- get first/last heart rate measurement during hospitalization for each stay_id\nWITH t1 AS\n(\n    select ce.stay_id\n    , min(charttime) as intime_hr\n    , max(charttime) as outtime_hr\n    FROM chartevents ce\n    -- only look at heart rate\n    where ce.itemid = 220045\n    group by ce.stay_id\n)\n-- add in subject_id/hadm_id\nselect\n  ie.subject_id, ie.hadm_id, ie.stay_id\n  , t1.intime_hr\n  , t1.outtime_hr\nFROM icustays ie\nleft join t1\n  on ie.stay_id = t1.stay_id;\n-- jing add tail\nalter table mimic4.demographics_icustay_times\nowner to postgres;"
icustay_hourly <- "SET client_min_messages TO WARNING;\nset search_path to mimic4;\nset search_path to mimic4;\ndrop materialized view if exists demographics_icustay_hourly;\ncreate materialized view mimic4.demographics_icustay_hourly\ntablespace pg_default\nas\nwith all_hours as\n(\nselect\n  it.stay_id\n  , PARSE_DATETIME(\n      '%Y-%m-%d %H:00:00',\n      FORMAT_DATETIME(\n        '%Y-%m-%d %H:00:00',\n          DATETIME_ADD(it.intime_hr, interval '1 MINUTE' * ('59'))\n  )) AS endtime\n\n  -- create integers for each charttime in hours from admission\n  -- so 0 is admission time, 1 is one hour after admission, etc, up to ICU disch\n  --  we allow 24 hours before ICU admission (to grab labs before admit)\n  , GENERATE_ARRAY(-24, CEIL(datetime_diff(it.outtime_hr, it.intime_hr, 'HOUR'))::integer) as hrs\n\n  from demographics_icustay_times it\n)\nSELECT stay_id\n, CAST(hr AS bigint) as hr\n, DATETIME_ADD(endtime, interval '1 HOUR' * (CAST(hr AS bigint))) as endtime\nFROM all_hours\nCROSS JOIN UNNEST(array[all_hours.hrs]) AS hr;\n-- jing add tail\nalter table mimic4.demographics_icustay_hourly\nowner to postgres;"


# comorbidity 1 -0
charlson <- "SET client_min_messages TO WARNING;\nSET client_min_messages TO WARNING;\nset search_path to mimic4;\ndrop materialized view if exists comorbidity_charlson;\ncreate materialized view mimic4.comorbidity_charlson\ntablespace pg_default\nas\n-- jing add head\nWITH diag AS\n(\n    SELECT \n        hadm_id\n        , CASE WHEN icd_version = 9 THEN icd_code ELSE NULL END AS icd9_code\n        , CASE WHEN icd_version = 10 THEN icd_code ELSE NULL END AS icd10_code\n    FROM diagnoses_icd diag\n)\n, com AS\n(\n    SELECT\n        ad.hadm_id\n\n        -- Myocardial infarction\n        , MAX(CASE WHEN\n            SUBSTR(icd9_code, 1, 3) IN ('410','412')\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('I21','I22')\n            OR\n            SUBSTR(icd10_code, 1, 4) = 'I252'\n            THEN 1 \n            ELSE 0 END) AS myocardial_infarct\n\n        -- Congestive heart failure\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) = '428'\n            OR\n            SUBSTR(icd9_code, 1, 5) IN ('39891','40201','40211','40291','40401','40403',\n                          '40411','40413','40491','40493')\n            OR \n            SUBSTR(icd9_code, 1, 4) BETWEEN '4254' AND '4259'\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('I43','I50')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('I099','I110','I130','I132','I255','I420',\n                                                   'I425','I426','I427','I428','I429','P290')\n            THEN 1 \n            ELSE 0 END) AS congestive_heart_failure\n\n        -- Peripheral vascular disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('440','441')\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('0930','4373','4471','5571','5579','V434')\n            OR\n            SUBSTR(icd9_code, 1, 4) BETWEEN '4431' AND '4439'\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('I70','I71')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('I731','I738','I739','I771','I790',\n                                                   'I792','K551','K558','K559','Z958','Z959')\n            THEN 1 \n            ELSE 0 END) AS peripheral_vascular_disease\n\n        -- Cerebrovascular disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) BETWEEN '430' AND '438'\n            OR\n            SUBSTR(icd9_code, 1, 5) = '36234'\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('G45','G46')\n            OR \n            SUBSTR(icd10_code, 1, 3) BETWEEN 'I60' AND 'I69'\n            OR\n            SUBSTR(icd10_code, 1, 4) = 'H340'\n            THEN 1 \n            ELSE 0 END) AS cerebrovascular_disease\n\n        -- Dementia\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) = '290'\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('2941','3312')\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('F00','F01','F02','F03','G30')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('F051','G311')\n            THEN 1 \n            ELSE 0 END) AS dementia\n\n
-- Chronic pulmonary disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) BETWEEN '490' AND '505'\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('4168','4169','5064','5081','5088')\n            OR \n            SUBSTR(icd10_code, 1, 3) BETWEEN 'J40' AND 'J47'\n            OR \n            SUBSTR(icd10_code, 1, 3) BETWEEN 'J60' AND 'J67'\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('I278','I279','J684','J701','J703')\n            THEN 1 \n            ELSE 0 END) AS chronic_pulmonary_disease\n\n\n-- Rheumatic disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) = '725'\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('4465','7100','7101','7102','7103',\n                                                  '7104','7140','7141','7142','7148')\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('M05','M06','M32','M33','M34')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('M315','M351','M353','M360')\n            THEN 1 \n            ELSE 0 END) AS rheumatic_disease\n\n        -- Peptic ulcer disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('531','532','533','534')\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('K25','K26','K27','K28')\n            THEN 1 \n            ELSE 0 END) AS peptic_ulcer_disease\n\n        -- Mild liver disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('570','571')\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('0706','0709','5733','5734','5738','5739','V427')\n            OR\n            SUBSTR(icd9_code, 1, 5) IN ('07022','07023','07032','07033','07044','07054')\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('B18','K73','K74')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('K700','K701','K702','K703','K709','K713',\n                                                   'K714','K715','K717','K760','K762',\n                                                   'K763','K764','K768','K769','Z944')\n            THEN 1 \n            ELSE 0 END) AS mild_liver_disease\n\n        -- Diabetes without chronic complication\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 4) IN ('2500','2501','2502','2503','2508','2509') \n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('E100','E10l','E106','E108','E109','E110','E111',\n                                                   'E116','E118','E119','E120','E121','E126','E128',\n                                                   'E129','E130','E131','E136','E138','E139','E140',\n                                                   'E141','E146','E148','E149')\n            THEN 1 \n            ELSE 0 END) AS diabetes_without_cc\n\n        -- Diabetes with chronic complication\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 4) IN ('2504','2505','2506','2507')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('E102','E103','E104','E105','E107','E112','E113',\n                                                   'E114','E115','E117','E122','E123','E124','E125',\n                                                   'E127','E132','E133','E134','E135','E137','E142',\n                                                   'E143','E144','E145','E147')\n            THEN 1 \n            ELSE 0 END) AS diabetes_with_cc\n\n
-- Hemiplegia or paraplegia\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('342','343')\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('3341','3440','3441','3442',\n                                                  '3443','3444','3445','3446','3449')\n            OR \n            SUBSTR(icd10_code, 1, 3) IN ('G81','G82')\n            OR \n            SUBSTR(icd10_code, 1, 4) IN ('G041','G114','G801','G802','G830',\n                                                   'G831','G832','G833','G834','G839')\n            THEN 1 \n            ELSE 0 END) AS paraplegia\n\n\n-- Renal disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('582','585','586','V56')\n            OR\n            SUBSTR(icd9_code, 1, 4) IN ('5880','V420','V451')\n            OR\n            SUBSTR(icd9_code, 1, 4) BETWEEN '5830' AND '5837'\n            OR\n            SUBSTR(icd9_code, 1, 5) IN ('40301','40311','40391','40402','40403','40412','40413','40492','40493')          \n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('N18','N19')\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('I120','I131','N032','N033','N034',\n                                                   'N035','N036','N037','N052','N053',\n                                                   'N054','N055','N056','N057','N250',\n                                                   'Z490','Z491','Z492','Z940','Z992')\n            THEN 1 \n            ELSE 0 END) AS renal_disease\n\n        -- Any malignancy, including lymphoma and leukemia, except malignant neoplasm of skin\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) BETWEEN '140' AND '172'\n            OR\n            SUBSTR(icd9_code, 1, 4) BETWEEN '1740' AND '1958'\n            OR\n            SUBSTR(icd9_code, 1, 3) BETWEEN '200' AND '208'\n            OR\n            SUBSTR(icd9_code, 1, 4) = '2386'\n            OR\n            SUBSTR(icd10_code, 1, 3) IN ('C43','C88')\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C00' AND 'C26'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C30' AND 'C34'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C37' AND 'C41'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C45' AND 'C58'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C60' AND 'C76'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C81' AND 'C85'\n            OR\n            SUBSTR(icd10_code, 1, 3) BETWEEN 'C90' AND 'C97'\n            THEN 1 \n            ELSE 0 END) AS malignant_cancer\n\n        -- Moderate or severe liver disease\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 4) IN ('4560','4561','4562')\n            OR\n            SUBSTR(icd9_code, 1, 4) BETWEEN '5722' AND '5728'\n            OR\n            SUBSTR(icd10_code, 1, 4) IN ('I850','I859','I864','I982','K704','K711',\n                                                   'K721','K729','K765','K766','K767')\n            THEN 1 \n            ELSE 0 END) AS severe_liver_disease\n\n
-- Metastatic solid tumor\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('196','197','198','199')\n            OR \n            SUBSTR(icd10_code, 1, 3) IN ('C77','C78','C79','C80')\n            THEN 1 \n            ELSE 0 END) AS metastatic_solid_tumor\n\n        -- AIDS/HIV\n        , MAX(CASE WHEN \n            SUBSTR(icd9_code, 1, 3) IN ('042','043','044')\n            OR \n            SUBSTR(icd10_code, 1, 3) IN ('B20','B21','B22','B24')\n            THEN 1 \n            ELSE 0 END) AS aids\n    FROM admissions ad\n    LEFT JOIN diag\n    ON ad.hadm_id = diag.hadm_id\n    GROUP BY ad.hadm_id\n)\n, ag AS\n(\n    SELECT \n        hadm_id\n        , age\n        , CASE WHEN age <= 40 THEN 0\n    WHEN age <= 50 THEN 1\n    WHEN age <= 60 THEN 2\n    WHEN age <= 70 THEN 3\n    ELSE 4 END AS age_score\n    FROM demographics_age\n)\nSELECT \n    ad.subject_id\n    , ad.hadm_id\n    , ag.age_score\n    , myocardial_infarct\n    , congestive_heart_failure\n    , peripheral_vascular_disease\n    , cerebrovascular_disease\n    , dementia\n    , chronic_pulmonary_disease\n    , rheumatic_disease\n    , peptic_ulcer_disease\n    , mild_liver_disease\n    , diabetes_without_cc\n    , diabetes_with_cc\n    , paraplegia\n    , renal_disease\n    , malignant_cancer\n    , severe_liver_disease \n    , metastatic_solid_tumor \n    , aids\n\n-- Calculate the charlson Comorbidity Score using the original\n    -- weights from charlson, 1987.\n    , age_score\n    + myocardial_infarct + congestive_heart_failure + peripheral_vascular_disease\n    + cerebrovascular_disease + dementia + chronic_pulmonary_disease\n    + rheumatic_disease + peptic_ulcer_disease\n    + GREATEST(mild_liver_disease, 3*severe_liver_disease)\n    + GREATEST(2*diabetes_with_cc, diabetes_without_cc)\n    + GREATEST(2*malignant_cancer, 6*metastatic_solid_tumor)\n    + 2*paraplegia + 2*renal_disease \n    + 6*aids\n    AS charlson_comorbidity_index\nFROM admissions ad\nLEFT JOIN com\nON ad.hadm_id = com.hadm_id\nLEFT JOIN ag\nON com.hadm_id = ag.hadm_id\n;\n-- jing add tail\nalter table mimic4.comorbidity_charlson\nowner to postgres;"

# duration 1 - 0

weight_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic4;\ndrop materialized view if exists durations_weight_durations;\ncreate materialized view mimic4.durations_weight_durations\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts weights for adult ICU patients with start/stop times\n-- if an admission weight is given, then this is assigned from intime to outtime\nWITH wt_stg as\n(\n    SELECT\n        c.stay_id\n      , c.charttime\n      , case when c.itemid = 226512 then 'admit'\n          else 'daily' end as weight_type\n      -- TODO: eliminate obvious outliers if there is a reasonable weight\n      , c.valuenum as weight\n    FROM chartevents c\n    WHERE c.valuenum IS NOT NULL\n      AND c.itemid in\n      (\n          226512 -- Admit Wt\n          , 224639 -- Daily Weight\n      )\n      AND c.valuenum > 0\n)\n-- assign ascending row number\n, wt_stg1 as\n(\n  select\n      stay_id\n    , charttime\n    , weight_type\n    , weight\n    , ROW_NUMBER() OVER (partition by stay_id, weight_type order by charttime) as rn\n  from wt_stg\n  WHERE weight IS NOT NULL\n)\n-- change charttime to intime for the first admission weight recorded\n, wt_stg2 AS\n(\n  SELECT \n      wt_stg1.stay_id\n    , ie.intime, ie.outtime\n    , wt_stg1.weight_type\n    , case when wt_stg1.weight_type = 'admit' and wt_stg1.rn = 1\n        then DATETIME_SUB(ie.intime, interval '1 HOUR' * ('2'))\n      else wt_stg1.charttime end as starttime\n    , wt_stg1.weight\n  from wt_stg1\n  INNER JOIN icustays ie\n    on ie.stay_id = wt_stg1.stay_id\n)\n, wt_stg3 as\n(\n  select\n    stay_id\n    , intime, outtime\n    , starttime\n    , coalesce(\n        LEAD(starttime) OVER (PARTITION BY stay_id ORDER BY starttime),\n        DATETIME_ADD(outtime, interval '1 HOUR' * ('2'))\n      ) as endtime\n    , weight\n    , weight_type\n  from wt_stg2\n)\n-- this table is the start/stop times from admit/daily weight in charted data\n, wt1 as\n(\n  select\n      stay_id\n    , starttime\n    , coalesce(endtime,\n      LEAD(starttime) OVER (partition by stay_id order by starttime),\n      -- impute ICU discharge as the end of the final weight measurement\n      -- plus a 2 hour \\\"fuzziness\\\" window\n      DATETIME_ADD(outtime, interval '1 HOUR' * ('2'))\n    ) as endtime\n    , weight\n    , weight_type\n  from wt_stg3\n)\n-- if the intime for the patient is < the first charted daily weight\n-- then we will have a \\\"gap\\\" at the start of their stay\n-- to prevent this, we look for these gaps and backfill the first weight\n-- this adds (153255-149657)=3598 rows, meaning this fix helps for up to 3598 stay_id\n, wt_fix as\n(\n  select ie.stay_id\n    -- we add a 2 hour \\\"fuzziness\\\" window\n    , DATETIME_SUB(ie.intime, interval '1 HOUR' * ('2')) as starttime\n    , wt.starttime as endtime\n    , wt.weight\n    , wt.weight_type\n  from icustays ie\n  inner join\n  -- the below subquery returns one row for each unique stay_id\n  -- the row contains: the first starttime and the corresponding weight\n  (\n    SELECT wt1.stay_id, wt1.starttime, wt1.weight\n    , weight_type\n    , ROW_NUMBER() OVER (PARTITION BY wt1.stay_id ORDER BY wt1.starttime) as rn\n    FROM wt1\n  ) wt\n    ON  ie.stay_id = wt.stay_id\n    AND wt.rn = 1\n    and ie.intime < wt.starttime\n)\n-- add the backfill rows to the main weight table\nSELECT\nwt1.stay_id\n, wt1.starttime\n, wt1.endtime\n, wt1.weight\n, wt1.weight_type\nFROM wt1\nUNION ALL\nSELECT\nwt_fix.stay_id\n, wt_fix.starttime\n, wt_fix.endtime\n, wt_fix.weight\n, wt_fix.weight_type\nFROM wt_fix;\n-- jing add tail\nalter table mimic4.durations_weight_durations\nowner to postgres;"

# measurement 18 - 0

bg <- "set search_path to mimic4;\ndrop materialized view if exists measurement_bg;\ncreate materialized view mimic4.measurement_bg\ntablespace pg_default\nas\n-- jing add head\n-- The aim of this query is to pivot entries related to blood gases\n-- which were found in LABEVENTS\nWITH bg AS\n(\nselect \n  -- specimen_id only ever has 1 measurement for each itemid\n  -- so, we may simply collapse rows using MAX()\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  -- specimen_id *may* have different storetimes, so this is taking the latest\n  , MAX(storetime) AS storetime\n  , le.specimen_id\n  , MAX(CASE WHEN itemid = 52028 THEN value ELSE NULL END) AS specimen\n  , MAX(CASE WHEN itemid = 50801 THEN valuenum ELSE NULL END) AS aado2\n  , MAX(CASE WHEN itemid = 50802 THEN valuenum ELSE NULL END) AS baseexcess\n  , MAX(CASE WHEN itemid = 50803 THEN valuenum ELSE NULL END) AS bicarbonate\n  , MAX(CASE WHEN itemid = 50804 THEN valuenum ELSE NULL END) AS totalco2\n  , MAX(CASE WHEN itemid = 50805 THEN valuenum ELSE NULL END) AS carboxyhemoglobin\n  , MAX(CASE WHEN itemid = 50806 THEN valuenum ELSE NULL END) AS chloride\n  , MAX(CASE WHEN itemid = 50808 THEN valuenum ELSE NULL END) AS calcium\n  , MAX(CASE WHEN itemid = 50809 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose\n  , MAX(CASE WHEN itemid = 50810 and valuenum <= 100 THEN valuenum ELSE NULL END) AS hematocrit\n  , MAX(CASE WHEN itemid = 50811 THEN valuenum ELSE NULL END) AS hemoglobin\n  , MAX(CASE WHEN itemid = 50813 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS lactate\n  , MAX(CASE WHEN itemid = 50814 THEN valuenum ELSE NULL END) AS methemoglobin\n  , MAX(CASE WHEN itemid = 50815 THEN valuenum ELSE NULL END) AS o2flow\n  -- fix a common unit conversion error for fio2\n  -- atmospheric o2 is 20.89%, so any value <= 20 is unphysiologic\n  -- usually this is a misplaced O2 flow measurement\n  , MAX(CASE WHEN itemid = 50816 THEN\n      CASE\n        WHEN valuenum > 20 AND valuenum <= 100 THEN valuenum \n        WHEN valuenum > 0.2 AND valuenum <= 1.0 THEN valuenum*100.0\n      ELSE NULL END\n    ELSE NULL END) AS fio2\n  , MAX(CASE WHEN itemid = 50817 AND valuenum <= 100 THEN valuenum ELSE NULL END) AS so2\n  , MAX(CASE WHEN itemid = 50818 THEN valuenum ELSE NULL END) AS pco2\n  , MAX(CASE WHEN itemid = 50819 THEN valuenum ELSE NULL END) AS peep\n  , MAX(CASE WHEN itemid = 50820 THEN valuenum ELSE NULL END) AS ph\n  , MAX(CASE WHEN itemid = 50821 THEN valuenum ELSE NULL END) AS po2\n  , MAX(CASE WHEN itemid = 50822 THEN valuenum ELSE NULL END) AS potassium\n  , MAX(CASE WHEN itemid = 50823 THEN valuenum ELSE NULL END) AS requiredo2\n  , MAX(CASE WHEN itemid = 50824 THEN valuenum ELSE NULL END) AS sodium\n  , MAX(CASE WHEN itemid = 50825 THEN valuenum ELSE NULL END) AS temperature\n  , MAX(CASE WHEN itemid = 50807 THEN value ELSE NULL END) AS comments\nFROM labevents le\nwhere le.ITEMID in\n-- blood gases\n(\n    52028 -- specimen\n  , 50801
    -- aado2\n  , 50802 -- base excess\n  , 50803 -- bicarb\n  , 50804 -- calc tot co2\n  , 50805 -- carboxyhgb\n  , 50806 -- chloride\n  -- , 52390 -- chloride, WB CL-\n  , 50807 -- comments\n  , 50808 -- free calcium\n  , 50809 -- glucose\n  , 50810 -- hct\n  , 50811 -- hgb\n  , 50813 -- lactate\n  , 50814 -- methemoglobin\n  , 50815 -- o2 flow\n  , 50816 -- fio2\n  , 50817 -- o2 sat\n  , 50818 -- pco2\n  , 50819 -- peep\n  , 50820 -- pH\n  , 50821 -- pO2\n  , 50822 -- potassium\n  -- , 52408 -- potassium, WB K+\n  , 50823 -- required O2\n  , 50824 -- sodium\n  -- , 52411 -- sodium, WB NA +\n  , 50825 -- temperature\n)\nGROUP BY le.specimen_id\n)\n, stg_spo2 as\n(\n  select subject_id, charttime\n    -- avg here is just used to group SpO2 by charttime\n    , AVG(valuenum) as SpO2\n  FROM chartevents\n  where ITEMID = 220277 -- O2 saturation pulseoxymetry\n  and valuenum > 0 and valuenum <= 100\n  group by subject_id, charttime\n)\n, stg_fio2 as\n(\n  select subject_id, charttime\n    -- pre-process the FiO2s to ensure they are between 21-100%\n    , max(\n        case\n          when valuenum > 0.2 and valuenum <= 1\n            then valuenum * 100\n          -- improperly input data - looks like O2 flow in litres\n          when valuenum > 1 and valuenum < 20\n            then null\n          when valuenum >= 20 and valuenum <= 100\n            then valuenum\n      else null end\n    ) as fio2_chartevents\n  FROM chartevents\n  where ITEMID = 223835 -- Inspired O2 Fraction (FiO2)\n  and valuenum > 0 and valuenum <= 100\n  group by subject_id, charttime\n)\n, stg2 as\n(\nselect bg.*\n  , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s1.charttime DESC) as lastRowSpO2\n  , s1.spo2\nfrom bg\nleft join stg_spo2 s1\n  -- same hospitalization\n  on  bg.subject_id = s1.subject_id\n  -- spo2 occurred at most 2 hours before this blood gas\n  and s1.charttime between DATETIME_SUB(bg.charttime, interval '1 HOUR' * (2)) and bg.charttime\nwhere bg.po2 is not null\n)\n, stg3 as\n(\nselect bg.*\n  , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s2.charttime DESC) as lastRowFiO2\n  , s2.fio2_chartevents\n  -- create our specimen prediction\n  ,  1/(1+exp(-(-0.02544\n  +    0.04598 * po2\n  + coalesce(-0.15356 * spo2             , -0.15356 *   97.49420 +    0.13429)\n  + coalesce( 0.00621 * fio2_chartevents ,  0.00621 *   51.49550 +   -0.24958)\n  + coalesce( 0.10559 * hemoglobin       ,  0.10559 *   10.32307 +    0.05954)\n  + coalesce( 0.13251 * so2              ,  0.13251 *   93.66539 +   -0.23172)\n  + coalesce(-0.01511 * pco2             , -0.01511 *   42.08866 +   -0.01630)\n  + coalesce( 0.01480 * fio2             ,  0.01480 *   63.97836 +   -0.31142)\n  + coalesce(-0.00200 * aado2            , -0.00200 *  442.21186 +   -0.01328)\n  + coalesce(-0.03220 * bicarbonate      , -0.03220 *   22.96894 +   -0.06535)\n  + coalesce( 0.05384 * totalco2         ,  0.05384 *   24.72632 +   -0.01405)\n  + coalesce( 0.08202 * lactate          ,  0.08202 *    3.06436 +    0.06038)\n  + coalesce( 0.10956 * ph               ,  0.10956 *    7.36233 +   -0.00617)\n  + coalesce( 0.00848 * o2flow           ,  0.00848 *    7.59362 +   -0.35803)\n  ))) as specimen_prob\nfrom stg2 bg\nleft join stg_fio2 s2\n
    -- same patient\n  on  bg.subject_id = s2.subject_id\n  -- fio2 occurred at most 4 hours before this blood gas\n  and s2.charttime between DATETIME_SUB(bg.charttime, interval '1 HOUR' * (4)) and bg.charttime\n  AND s2.fio2_chartevents > 0\nwhere bg.lastRowSpO2 = 1 -- only the row with the most recent SpO2 (if no SpO2 found lastRowSpO2 = 1)\n)\nselect\n    stg3.subject_id\n  , stg3.hadm_id\n  , stg3.charttime\n  -- raw data indicating sample type\n  , specimen \n  -- prediction of specimen for obs missing the actual specimen\n  , case\n        when specimen is not null then specimen\n        when specimen_prob > 0.75 then 'ART.'\n      else null end as specimen_pred\n  , specimen_prob\n  -- oxygen related parameters\n  , so2\n  , po2\n  , pco2\n  , fio2_chartevents, fio2\n  , aado2\n  -- also calculate AADO2\n  , case\n      when  po2 is null\n        OR pco2 is null\n      THEN NULL\n      WHEN fio2 IS NOT NULL\n        -- multiple by 100 because fio2 is in a % but should be a fraction\n        THEN (fio2/100) * (760 - 47) - (pco2/0.8) - po2\n      WHEN fio2_chartevents IS NOT NULL\n        THEN (fio2_chartevents/100) * (760 - 47) - (pco2/0.8) - po2\n      else null\n    end as aado2_calc\n  , case\n      when PO2 is null\n        THEN NULL\n      WHEN fio2 IS NOT NULL\n       -- multiply by 100 because fio2 is in a % but should be a fraction\n        then 100 * PO2/fio2\n      WHEN fio2_chartevents IS NOT NULL\n       -- multiply by 100 because fio2 is in a % but should be a fraction\n        then 100 * PO2/fio2_chartevents\n      else null\n    end as pao2fio2ratio\n  -- acid-base parameters\n  , ph, baseexcess\n  , bicarbonate, totalco2\n  -- blood count parameters\n  , hematocrit\n  , hemoglobin\n  , carboxyhemoglobin\n  , methemoglobin\n  -- chemistry\n  , chloride, calcium\n  , temperature\n  , potassium, sodium\n  , lactate\n  , glucose\n  -- ventilation stuff that's sometimes input\n  -- , intubated, tidalvolume, ventilationrate, ventilator\n  -- , peep, o2flow\n  -- , requiredo2\nfrom stg3\nwhere lastRowFiO2 = 1 -- only the most recent FiO2\n;\n-- jing add tail\nalter table mimic4.measurement_bg\nowner to postgres;"
blood_differential <- "set search_path to mimic4;\ndrop materialized view if exists measurement_blood_differential;\ncreate materialized view mimic4.measurement_blood_differential\ntablespace pg_default\nas\n-- jing add head\n-- For reference, some common unit conversions:\n-- 10^9/L == K/uL == 10^3/uL\nWITH blood_diff AS\n(\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- create one set of columns for percentages, and one set of columns for counts\n  -- we harmonize all count units into K/uL == 10^9/L\n  -- counts have an \\\"_abs\\\" suffix, percentages do not\n  -- absolute counts\n  , MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) AS wbc\n  , MAX(CASE WHEN itemid = 52069 THEN valuenum ELSE NULL END) AS basophils_abs\n  -- 52073 in K/uL, 51199 in #/uL\n  , MAX(CASE WHEN itemid = 52073 THEN valuenum WHEN itemid = 51199 THEN valuenum / 1000.0 ELSE NULL END) AS eosinophils_abs\n  -- 51133 in K/uL, 52769 in #/uL\n  , MAX(CASE WHEN itemid = 51133 THEN valuenum WHEN itemid = 52769 THEN valuenum / 1000.0 ELSE NULL END) AS lymphocytes_abs\n  -- 52074 in K/uL, 51253 in #/uL\n  , MAX(CASE WHEN itemid = 52074 THEN valuenum WHEN itemid = 51253 THEN valuenum / 1000.0 ELSE NULL END) AS monocytes_abs\n  , MAX(CASE WHEN itemid = 52075 THEN valuenum ELSE NULL END) AS neutrophils_abs\n  -- convert from #/uL to K/uL\n  , MAX(CASE WHEN itemid = 51218 THEN valuenum / 1000.0 ELSE NULL END) AS granulocytes_abs\n  -- percentages, equal to cell count / white blood cell count\n  , MAX(CASE WHEN itemid = 51146 THEN valuenum ELSE NULL END) AS basophils\n  , MAX(CASE WHEN itemid = 51200 THEN valuenum ELSE NULL END) AS eosinophils\n  , MAX(CASE WHEN itemid in (51244, 51245) THEN valuenum ELSE NULL END) AS lymphocytes\n  , MAX(CASE WHEN itemid = 51254 THEN valuenum ELSE NULL END) AS monocytes\n  , MAX(CASE WHEN itemid = 51256 THEN valuenum ELSE NULL END) AS neutrophils\n  -- other cell count percentages\n  , MAX(CASE WHEN itemid = 51143 THEN valuenum ELSE NULL END) AS atypical_lymphocytes\n  , MAX(CASE WHEN itemid = 51144 THEN valuenum ELSE NULL END) AS bands\n  , MAX(CASE WHEN itemid = 52135 THEN valuenum ELSE NULL END) AS immature_granulocytes\n  , MAX(CASE WHEN itemid = 51251 THEN valuenum ELSE NULL END) AS metamyelocytes\n  , MAX(CASE WHEN itemid = 51257 THEN valuenum ELSE NULL END) AS nrbc\n
    -- utility flags which determine whether imputation is possible\n  , CASE\n    -- WBC is available\n    WHEN MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) > 0\n    -- and we have at least one percentage from the diff\n    -- sometimes the entire diff is 0%, which looks like bad data\n    AND SUM(CASE WHEN itemid IN (51146, 51200, 51244, 51245, 51254, 51256) THEN valuenum ELSE NULL END) > 0\n    THEN 1 ELSE 0 END AS impute_abs\nFROM labevents le\nWHERE le.itemid IN\n(\n    51146, -- basophils\n    52069, -- Absolute basophil count\n    51199, -- Eosinophil Count\n    51200, -- Eosinophils\n    52073, -- Absolute Eosinophil count\n    51244, -- Lymphocytes\n    51245, -- Lymphocytes, Percent\n    51133, -- Absolute Lymphocyte Count\n    52769, -- Absolute Lymphocyte Count\n    51253, -- Monocyte Count\n    51254, -- Monocytes\n    52074, -- Absolute Monocyte Count\n    51256, -- Neutrophils\n    52075, -- Absolute Neutrophil Count\n    51143, -- Atypical lymphocytes\n    51144, -- Bands (%)\n    51218, -- Granulocyte Count\n    52135, -- Immature granulocytes (%)\n    51251, -- Metamyelocytes\n    51257,  -- Nucleated Red Cells\n    -- wbc totals measured in K/uL\n    51300, 51301, 51755\n    -- 52220 (wbcp) is percentage\n\n    -- below are point of care tests which are extremely infrequent and usually low quality\n    -- 51697, -- Neutrophils (mmol/L)\n\n    -- below itemid do not have data as of MIMIC-IV v1.0\n    -- 51536, -- Absolute Lymphocyte Count\n    -- 51537, -- Absolute Neutrophil\n    -- 51690, -- Lymphocytes\n    -- 52151, -- NRBC\n)\nAND valuenum IS NOT NULL\n-- differential values cannot be negative\nAND valuenum >= 0\nGROUP BY le.specimen_id\n)\nSELECT \nsubject_id, hadm_id, charttime, specimen_id\n, wbc\n-- impute absolute count if percentage & WBC is available\n, ROUND(cast(CASE\n\t\t\t WHEN basophils_abs IS NULL AND basophils IS NOT NULL AND impute_abs = 1\n\t\t\t THEN basophils * wbc\n\t\t\t ELSE basophils_abs\n\t\t\t END\n\t\tas numeric), \t \n\t\t4) AS basophils_abs\n, ROUND(cast(CASE\n\t\t\t WHEN eosinophils_abs IS NULL AND eosinophils IS NOT NULL AND impute_abs = 1\n\t\t\t THEN eosinophils * wbc\n\t\t\t ELSE eosinophils_abs\n\t\t\t END\n\t\tas numeric), \t\t\t \n\t\t\t 4) AS eosinophils_abs\n, ROUND(cast(CASE\n\t\t\t WHEN lymphocytes_abs IS NULL AND lymphocytes IS NOT NULL AND impute_abs = 1\n\t\t\t THEN lymphocytes * wbc\n\t\t\t ELSE lymphocytes_abs\n\t\t\t END \n\t\tas numeric),\n\t\t\t 4) AS lymphocytes_abs\n, ROUND(cast(CASE\n\t\t\t WHEN monocytes_abs IS NULL AND monocytes IS NOT NULL AND impute_abs = 1\n\t\t\t THEN monocytes * wbc\n\t\t\t ELSE monocytes_abs\n\t\t\t END \n\t\tas numeric), \n\t\t4) AS monocytes_abs\n, ROUND(cast(CASE\n\t\t\t WHEN neutrophils_abs IS NULL AND neutrophils IS NOT NULL AND impute_abs = 1\n\t\t\t THEN neutrophils * wbc\n\t\t\t ELSE neutrophils_abs\n\t\t\t END \n\t\tas numeric),\n\t\t4) AS neutrophils_abs\n, basophils\n, eosinophils\n, lymphocytes\n, monocytes\n, neutrophils\n-- impute bands/blasts?\n, atypical_lymphocytes\n, bands\n, immature_granulocytes\n, metamyelocytes\n, nrbc\nFROM blood_diff\n;\n-- jing add tail\nalter table mimic4.measurement_blood_differential\nowner to postgres;"
cardiac_marker <- "set search_path to mimic4;\ndrop materialized view if exists measurement_cardiac_marker;\ncreate materialized view mimic4.measurement_cardiac_marker\ntablespace pg_default\nas\n-- jing add head\n-- begin query that extracts the data\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 51002 THEN value ELSE NULL END) AS troponin_i\n  , MAX(CASE WHEN itemid = 51003 THEN value ELSE NULL END) AS troponin_t\n  , MAX(CASE WHEN itemid = 50911 THEN valuenum ELSE NULL END) AS ck_mb\nFROM labevents le\nWHERE le.itemid IN\n(\n    -- 51002, -- Troponin I (troponin-I is not measured in MIMIC-IV)\n    -- 52598, -- Troponin I, point of care, rare/poor quality\n    51003, -- Troponin T\n    50911  -- Creatinine Kinase, MB isoenzyme\n)\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_cardiac_marker\nowner to postgres;"
chemistry <- "set search_path to mimic4;\ndrop materialized view if exists measurement_chemistry;\ncreate materialized view mimic4.measurement_chemistry\ntablespace pg_default\nas\n-- jing add head\nSELECT \n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 50862 AND valuenum <=    10 THEN valuenum ELSE NULL END) AS albumin\n  , MAX(CASE WHEN itemid = 50930 AND valuenum <=    10 THEN valuenum ELSE NULL END) AS globulin\n  , MAX(CASE WHEN itemid = 50976 AND valuenum <=    20 THEN valuenum ELSE NULL END) AS total_protein\n  , MAX(CASE WHEN itemid = 50868 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS aniongap\n  , MAX(CASE WHEN itemid = 50882 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS bicarbonate\n  , MAX(CASE WHEN itemid = 51006 AND valuenum <=   300 THEN valuenum ELSE NULL END) AS bun\n  , MAX(CASE WHEN itemid = 50893 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS calcium\n  , MAX(CASE WHEN itemid = 50902 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS chloride\n  , MAX(CASE WHEN itemid = 50912 AND valuenum <=   150 THEN valuenum ELSE NULL END) AS creatinine\n  , MAX(CASE WHEN itemid = 50931 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose\n  , MAX(CASE WHEN itemid = 50983 AND valuenum <=   200 THEN valuenum ELSE NULL END) AS sodium\n  , MAX(CASE WHEN itemid = 50971 AND valuenum <=    30 THEN valuenum ELSE NULL END) AS potassium\nFROM labevents le\nWHERE le.itemid IN\n(\n  -- comment is: LABEL | CATEGORY | FLUID | NUMBER OF ROWS IN LABEVENTS\n  50862, -- ALBUMIN | chemistry | BLOOD | 146697\n  50930, -- Globulin\n  50976, -- Total protein\n  50868, -- ANION GAP | chemistry | BLOOD | 769895\n  -- 52456, -- Anion gap, point of care test\n  50882, -- BICARBONATE | chemistry | BLOOD | 780733\n  50893, -- Calcium\n  50912, -- CREATININE | chemistry | BLOOD | 797476\n  -- 52502, Creatinine, point of care\n  50902, -- CHLORIDE | chemistry | BLOOD | 795568\n  50931, -- GLUCOSE | chemistry | BLOOD | 748981\n  -- 52525, Glucose, point of care\n  50971, -- POTASSIUM | chemistry | BLOOD | 845825\n  -- 52566, -- Potassium, point of care\n  50983, -- SODIUM | chemistry | BLOOD | 808489\n  -- 52579, -- Sodium, point of care\n  51006  -- UREA NITROGEN | chemistry | BLOOD | 791925\n  -- 52603, Urea, point of care\n)\nAND valuenum IS NOT NULL\n-- lab values cannot be 0 and cannot be negative\n-- .. except anion gap.\nAND (valuenum > 0 OR itemid = 50868)\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_chemistry\nowner to postgres;"
coagulation <- "set search_path to mimic4;\ndrop materialized view if exists measurement_coagulation;\ncreate materialized view mimic4.measurement_coagulation\ntablespace pg_default\nas\n-- jing add head\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 51196 THEN valuenum ELSE NULL END) AS d_dimer\n  , MAX(CASE WHEN itemid = 51214 THEN valuenum ELSE NULL END) AS fibrinogen\n  , MAX(CASE WHEN itemid = 51297 THEN valuenum ELSE NULL END) AS thrombin\n  , MAX(CASE WHEN itemid = 51237 THEN valuenum ELSE NULL END) AS inr\n  , MAX(CASE WHEN itemid = 51274 THEN valuenum ELSE NULL END) AS pt\n  , MAX(CASE WHEN itemid = 51275 THEN valuenum ELSE NULL END) AS ptt\nFROM labevents le\nWHERE le.itemid IN\n(\n    -- 51149, 52750, 52072, 52073 -- Bleeding Time, no data as of MIMIC-IV v0.4\n    51196, -- D-Dimer\n    51214, -- Fibrinogen\n    -- 51280, 52893, -- Reptilase Time, no data as of MIMIC-IV v0.4\n    -- 51281, 52161, -- Reptilase Time Control, no data as of MIMIC-IV v0.4\n    51297, -- thrombin\n    51237, -- INR\n    51274, -- PT\n    51275 -- PTT\n)\nAND valuenum IS NOT NULL\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_coagulation\nowner to postgres;"
complete_blood_count <- "set search_path to mimic4;\ndrop materialized view if exists measurement_complete_blood_count;\ncreate materialized view mimic4.measurement_complete_blood_count\ntablespace pg_default\nas\n-- jing add head\n-- begin query that extracts the data\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 51221 THEN valuenum ELSE NULL END) AS hematocrit\n  , MAX(CASE WHEN itemid = 51222 THEN valuenum ELSE NULL END) AS hemoglobin\n  , MAX(CASE WHEN itemid = 51248 THEN valuenum ELSE NULL END) AS mch\n  , MAX(CASE WHEN itemid = 51249 THEN valuenum ELSE NULL END) AS mchc\n  , MAX(CASE WHEN itemid = 51250 THEN valuenum ELSE NULL END) AS mcv\n  , MAX(CASE WHEN itemid = 51265 THEN valuenum ELSE NULL END) AS platelet\n  , MAX(CASE WHEN itemid = 51279 THEN valuenum ELSE NULL END) AS rbc\n  , MAX(CASE WHEN itemid = 51277 THEN valuenum ELSE NULL END) AS rdw\n  , MAX(CASE WHEN itemid = 52159 THEN valuenum ELSE NULL END) AS rdwsd\n  , MAX(CASE WHEN itemid = 51301 THEN valuenum ELSE NULL END) AS wbc\nFROM labevents le\nWHERE le.itemid IN\n(\n    51221, -- hematocrit\n    51222, -- hemoglobin\n    51248, -- MCH\n    51249, -- MCHC\n    51250, -- MCV\n    51265, -- platelets\n    51279, -- RBC\n    51277, -- RDW\n    52159, -- RDW SD\n    51301  -- WBC\n\n)\nAND valuenum IS NOT NULL\n-- lab values cannot be 0 and cannot be negative\nAND valuenum > 0\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_complete_blood_count\nowner to postgres;"
creatinine_baseline <- "set search_path to mimic4;\ndrop materialized view if exists measurement_creatinine_baseline;\ncreate materialized view mimic4.measurement_creatinine_baseline\ntablespace pg_default\nas\n-- jing add head\nWITH p as\n(\n    SELECT \n        ag.subject_id\n        , ag.hadm_id\n        , ag.age\n        , p.gender\n        , CASE WHEN p.gender='F' THEN \n            POWER(75.0 / 186.0 / POWER(ag.age, -0.203) / 0.742, -1/1.154)\n            ELSE \n            POWER(75.0 / 186.0 / POWER(ag.age, -0.203), -1/1.154)\n            END \n            AS MDRD_est\n    FROM demographics_age ag\n    LEFT JOIN patients p\n    ON ag.subject_id = p.subject_id\n    WHERE ag.age >= 18\n)\n, lab as\n(\n    SELECT \n        hadm_id\n        , MIN(creatinine) AS scr_min\n    FROM measurement_chemistry\n    GROUP BY hadm_id\n)\n, ckd as \n(\n    SELECT hadm_id, MAX(1) AS CKD_flag\n    FROM diagnoses_icd\n    WHERE \n        (\n            SUBSTR(icd_code, 1, 3) = '585'\n            AND \n            icd_version = 9\n        )\n    OR \n        (\n            SUBSTR(icd_code, 1, 3) = 'N18'\n            AND \n            icd_version = 10\n        )\n    GROUP BY 1\n)\nSELECT \n    p.hadm_id\n    , p.gender\n    , p.age\n    , lab.scr_min\n    , COALESCE(ckd.ckd_flag, 0) AS ckd\n    , p.MDRD_est\n    , CASE \n    WHEN lab.scr_min<=1.1 THEN scr_min\n    WHEN ckd.ckd_flag=1 THEN scr_min\n    ELSE MDRD_est END AS scr_baseline\nFROM p\nLEFT JOIN lab\nON p.hadm_id = lab.hadm_id\nLEFT JOIN ckd\nON p.hadm_id = ckd.hadm_id\n;\n;\n-- jing add tail\nalter table mimic4.measurement_creatinine_baseline\nowner to postgres;"
enzyme <- "set search_path to mimic4;\ndrop materialized view if exists measurement_enzyme;\ncreate materialized view mimic4.measurement_enzyme\ntablespace pg_default\nas\n-- jing add head\n-- begin query that extracts the data\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 50861 THEN valuenum ELSE NULL END) AS alt\n  , MAX(CASE WHEN itemid = 50863 THEN valuenum ELSE NULL END) AS alp\n  , MAX(CASE WHEN itemid = 50878 THEN valuenum ELSE NULL END) AS ast\n  , MAX(CASE WHEN itemid = 50867 THEN valuenum ELSE NULL END) AS amylase\n  , MAX(CASE WHEN itemid = 50885 THEN valuenum ELSE NULL END) AS bilirubin_total\n  , MAX(CASE WHEN itemid = 50883 THEN valuenum ELSE NULL END) AS bilirubin_direct\n  , MAX(CASE WHEN itemid = 50884 THEN valuenum ELSE NULL END) AS bilirubin_indirect\n  , MAX(CASE WHEN itemid = 50910 THEN valuenum ELSE NULL END) AS ck_cpk\n  , MAX(CASE WHEN itemid = 50911 THEN valuenum ELSE NULL END) AS ck_mb\n  , MAX(CASE WHEN itemid = 50927 THEN valuenum ELSE NULL END) AS ggt\n  , MAX(CASE WHEN itemid = 50954 THEN valuenum ELSE NULL END) AS ld_ldh\nFROM labevents le\nWHERE le.itemid IN\n(\n    50861, -- Alanine transaminase (ALT)\n    50863, -- Alkaline phosphatase (ALP)\n    50878, -- Aspartate transaminase (AST)\n    50867, -- Amylase\n    50885, -- total bili\n    50884, -- indirect bili\n    50883, -- direct bili\n    50910, -- ck_cpk\n    50911, -- CK-MB\n    50927, -- Gamma Glutamyltransferase (GGT)\n    50954 -- ld_ldh\n)\nAND valuenum IS NOT NULL\n-- lab values cannot be 0 and cannot be negative\nAND valuenum > 0\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_enzyme\nowner to postgres;"
gcs <- "set search_path to mimic4;\ndrop materialized view if exists measurement_gcs;\ncreate materialized view mimic4.measurement_gcs\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts the Glasgow Coma Scale, a measure of neurological function.\n-- The query has a few special rules:\n--    (1) The verbal component can be set to 0 if the patient is ventilated.\n--    This is corrected to 5 - the overall gcs is set to 15 in these cases.\n--    (2) Often only one of three components is documented. The other components\n--    are carried forward.\n\n-- ITEMIDs used:\n\n-- METAVISION\n--    223900 gcs - Verbal Response\n--    223901 gcs - Motor Response\n--    220739 gcs - Eye Opening\n\n-- Note:\n--  The gcs for sedated patients is defaulted to 15 in this code.\n--  This is in line with how the data is meant to be collected.\n--  e.g., from the SAPS II publication:\n--    For sedated patients, the Glasgow Coma Score before sedation was used.\n--    This was ascertained either from interviewing the physician who ordered the sedation,\n--    or by reviewing the patient's medical record.\nwith base as\n(\n  select \n    subject_id\n  , ce.stay_id, ce.charttime\n  -- pivot each value into its own column\n  , max(case when ce.ITEMID = 223901 then ce.valuenum else null end) as gcsMotor\n  , max(case\n      when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 0\n      when ce.ITEMID = 223900 then ce.valuenum\n      else null \n    end) as gcsVerbal\n  , max(case when ce.ITEMID = 220739 then ce.valuenum else null end) as gcsEyes\n  -- convert the data into a number, reserving a value of 0 for ET/Trach\n  , max(case\n      -- endotrach/vent is assigned a value of 0\n      -- flag it here to later parse specially\n      when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 1 -- metavision\n    else 0 end)\n    as endotrachflag\n  , ROW_NUMBER ()\n          OVER (PARTITION BY ce.stay_id ORDER BY ce.charttime ASC) as rn\n  from chartevents ce\n  -- Isolate the desired gcs variables\n  where ce.ITEMID in\n  (\n    -- gcs components, Metavision\n    223900, 223901, 220739\n  )\n  group by ce.subject_id, ce.stay_id, ce.charttime\n)\n, gcs as (\n  select b.*\n  , b2.GCSVerbal as gcsVerbalPrev\n  , b2.GCSMotor as gcsMotorPrev\n  , b2.GCSEyes as gcsEyesPrev\n  -- Calculate gcs, factoring in special case when they are intubated and prev vals\n  -- note that the coalesce are used to implement the following if:\n
    --  if current value exists, use it\n  --  if previous value exists, use it\n  --  otherwise, default to normal\n  , case\n      -- replace gcs during sedation with 15\n      when b.GCSVerbal = 0\n        then 15\n      when b.GCSVerbal is null and b2.GCSVerbal = 0\n        then 15\n      -- if previously they were intub, but they aren't now, do not use previous gcs values\n      when b2.GCSVerbal = 0\n        then\n            coalesce(b.GCSMotor,6)\n          + coalesce(b.GCSVerbal,5)\n          + coalesce(b.GCSEyes,4)\n      -- otherwise, add up score normally, imputing previous value if none available at current time\n      else\n            coalesce(b.GCSMotor,coalesce(b2.GCSMotor,6))\n          + coalesce(b.GCSVerbal,coalesce(b2.GCSVerbal,5))\n          + coalesce(b.GCSEyes,coalesce(b2.GCSEyes,4))\n      end as gcs\n\n  from base b\n  -- join to itself within 6 hours to get previous value\n  left join base b2\n    on b.stay_id = b2.stay_id\n    and b.rn = b2.rn+1\n    and b2.charttime > DATETIME_ADD(b.charttime, interval '1 HOUR' * (6))\n)\n-- combine components with previous within 6 hours\n-- filter down to cohort which is not excluded\n-- truncate charttime to the hour\n, gcs_stg as\n(\n  select\n    subject_id\n  , gs.stay_id, gs.charttime\n  , gcs\n  , coalesce(GCSMotor,GCSMotorPrev) as gcsMotor\n  , coalesce(GCSVerbal,GCSVerbalPrev) as gcsVerbal\n  , coalesce(GCSEyes,GCSEyesPrev) as gcsEyes\n  , case when coalesce(GCSMotor,GCSMotorPrev) is null then 0 else 1 end\n  + case when coalesce(GCSVerbal,GCSVerbalPrev) is null then 0 else 1 end\n  + case when coalesce(GCSEyes,GCSEyesPrev) is null then 0 else 1 end\n    as components_measured\n  , EndoTrachFlag\n  from gcs gs\n)\n-- priority is:\n--  (i) complete data, (ii) non-sedated gcs, (iii) lowest gcs, (iv) charttime\n, gcs_priority as\n(\n  select \n      subject_id\n    , stay_id\n    , charttime\n    , gcs\n    , gcsmotor\n    , gcsverbal\n    , gcseyes\n    , EndoTrachFlag\n    , ROW_NUMBER() over\n      (\n        PARTITION BY stay_id, charttime\n        ORDER BY components_measured DESC, endotrachflag, gcs, charttime DESC\n      ) as rn\n  from gcs_stg\n)\nselect\n  gs.subject_id\n  , gs.stay_id\n  , gs.charttime\n  , gcs AS gcs\n  , gcsMotor AS gcs_motor\n  , gcsVerbal AS gcs_verbal\n  , gcsEyes AS gcs_eyes\n  , EndoTrachFlag AS gcs_unable\nfrom gcs_priority gs\nwhere rn = 1\n;\n-- jing add tail\nalter table mimic4.measurement_gcs\nowner to postgres;"
height <- "set search_path to mimic4;\ndrop materialized view if exists measurement_height;\ncreate materialized view mimic4.measurement_height\ntablespace pg_default\nas\n-- jing add head\n-- prep height\nWITH ht_in AS\n(\n  SELECT \n    c.subject_id, c.stay_id, c.charttime\n    -- Ensure that all heights are in centimeters\n    , ROUND(cast(c.valuenum * 2.54 as numeric), 2) AS height\n    , c.valuenum as height_orig\n  FROM chartevents c\n  WHERE c.valuenum IS NOT NULL\n  -- height (measured in inches)\n  AND c.itemid = 226707\n)\n, ht_cm AS\n(\n  SELECT \n    c.subject_id, c.stay_id, c.charttime\n    -- Ensure that all heights are in centimeters\n    , ROUND(cast(c.valuenum as numeric), 2) AS height\n  FROM chartevents c\n  WHERE c.valuenum IS NOT NULL\n  -- height cm\n  AND c.itemid = 226730\n)\n-- merge cm/height, only take 1 value per charted row\n, ht_stg0 AS\n(\n  SELECT\n  COALESCE(h1.subject_id, h1.subject_id) as subject_id\n  , COALESCE(h1.stay_id, h1.stay_id) AS stay_id\n  , COALESCE(h1.charttime, h1.charttime) AS charttime\n  , COALESCE(h1.height, h2.height) as height\n  FROM ht_cm h1\n  FULL OUTER JOIN ht_in h2\n    ON h1.subject_id = h2.subject_id\n    AND h1.charttime = h2.charttime\n)\nSELECT subject_id, stay_id, charttime, height\nFROM ht_stg0\nWHERE height IS NOT NULL\n-- filter out bad heights\nAND height > 120 AND height < 230;\n-- jing add tail\nalter table mimic4.measurement_height\nowner to postgres;"
icp <- "set search_path to mimic4;\ndrop materialized view if exists measurement_icp;\ncreate materialized view mimic4.measurement_icp\ntablespace pg_default\nas\n-- jing add head\nwith ce as\n(\n  select\n  ce.subject_id\n  , ce.stay_id\n  , ce.charttime\n  -- TODO: handle high icps when monitoring two icps\n  , case when valuenum > 0 and valuenum < 100 then valuenum else null end as icp\n  FROM chartevents ce\n  -- exclude rows marked as error\n  where ce.itemid in\n  (\n    220765 -- Intra Cranial Pressure -- 92306\n  , 227989 -- Intra Cranial Pressure #2 -- 1052\n  )\n)\nselect\n  ce.subject_id\n  , ce.stay_id\n  , ce.charttime\n  , MAX(icp) as icp\nfrom ce\ngroup by ce.subject_id, ce.stay_id, ce.charttime\n;\n-- jing add tail\nalter table mimic4.measurement_icp\nowner to postgres;"
inflammation <- "set search_path to mimic4;\ndrop materialized view if exists measurement_inflammation;\ncreate materialized view mimic4.measurement_inflammation\ntablespace pg_default\nas\n-- jing add head\nSELECT\n    MAX(subject_id) AS subject_id\n  , MAX(hadm_id) AS hadm_id\n  , MAX(charttime) AS charttime\n  , le.specimen_id\n  -- convert from itemid into a meaningful column\n  , MAX(CASE WHEN itemid = 50889 THEN valuenum ELSE NULL END) AS crp\n  -- , CAST(NULL AS NUMERIC) AS il6\n  -- , CAST(NULL AS NUMERIC) AS procalcitonin\nFROM labevents le\nWHERE le.itemid IN\n(\n    50889 -- crp\n    -- 51652 -- high sensitivity CRP\n)\nAND valuenum IS NOT NULL\n-- lab values cannot be 0 and cannot be negative\nAND valuenum > 0\nGROUP BY le.specimen_id\n;\n-- jing add tail\nalter table mimic4.measurement_inflammation\nowner to postgres;"
oxygen_delivery <- "set search_path to mimic4;\ndrop materialized view if exists measurement_oxygen_delivery;\ncreate materialized view mimic4.measurement_oxygen_delivery\ntablespace pg_default\nas\n-- jing add head\nwith ce_stg1 as\n(\n  SELECT\n      ce.subject_id\n    , ce.stay_id\n    , ce.charttime\n    , CASE\n        -- merge o2 flows into a single row\n        WHEN itemid IN (223834, 227582, 224691) THEN 223834\n      ELSE itemid END AS itemid\n    , value\n    , valuenum\n    , valueuom\n    , storetime\n  FROM chartevents ce\n  WHERE ce.value IS NOT NULL\n  AND ce.itemid IN\n  (\n      223834 -- o2 flow\n    , 227582 -- bipap o2 flow\n    , 224691 -- Flow Rate (L)\n    -- additional o2 flow is its own column\n    , 227287 -- additional o2 flow\n  )\n)\n, ce_stg2 AS\n(\n  select\n    ce.subject_id\n    , ce.stay_id\n    , ce.charttime\n    , itemid\n    , value\n    , valuenum\n    , valueuom\n    -- retain only 1 row per charttime\n    -- prioritizing the last documented value\n    -- primarily used to subselect o2 flows\n    , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY storetime DESC) as rn\n  FROM ce_stg1 ce\n)\n, o2 AS\n(\n    -- The below ITEMID can have multiple entires for charttime/storetime\n    -- These are totally valid entries, and should be retained in derived tables.\n    --   224181 -- Small Volume Neb Drug #1              | Respiratory             | Text       | chartevents\n
    -- , 227570 -- Small Volume Neb Drug/Dose #1         | Respiratory             | Text       | chartevents\n    -- , 224833 -- SBT Deferred                          | Respiratory             | Text       | chartevents\n    -- , 224716 -- SBT Stopped                           | Respiratory             | Text       | chartevents\n    -- , 224740 -- RSBI Deferred                         | Respiratory             | Text       | chartevents\n    -- , 224829 -- Trach Tube Type                       | Respiratory             | Text       | chartevents\n    -- , 226732 -- O2 Delivery Device(s)                 | Respiratory             | Text       | chartevents\n    -- , 226873 -- Inspiratory Ratio                     | Respiratory             | Numeric    | chartevents\n    -- , 226871 -- Expiratory Ratio                      | Respiratory             | Numeric    | chartevents\n    -- maximum of 4 o2 devices on at once\n    SELECT\n        subject_id\n        , stay_id\n        , charttime\n        , itemid\n        , value AS o2_device\n    , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY value) as rn\n    FROM chartevents\n    WHERE itemid = 226732 -- oxygen delivery device(s)\n)\n, stg AS\n(\n    select\n      COALESCE(ce.subject_id, o2.subject_id) AS subject_id\n    , COALESCE(ce.stay_id, o2.stay_id) AS stay_id\n    , COALESCE(ce.charttime, o2.charttime) AS charttime\n    , COALESCE(ce.itemid, o2.itemid) AS itemid\n    , ce.value\n    , ce.valuenum\n    , o2.o2_device\n    , o2.rn\n    from ce_stg2 ce\n    FULL OUTER JOIN o2\n      ON ce.subject_id = o2.subject_id\n      AND ce.charttime = o2.charttime\n    -- limit to 1 row per subject_id/charttime/itemid from ce_stg2\n    WHERE ce.rn = 1\n)\nSELECT\n    subject_id\n    , MAX(stay_id) AS stay_id\n    , charttime\n    , MAX(CASE WHEN itemid = 223834 THEN valuenum ELSE NULL END) AS o2_flow\n    , MAX(CASE WHEN itemid = 227287 THEN valuenum ELSE NULL END) AS o2_flow_additional\n    -- ensure we retain all o2 devices for the patient\n    , MAX(CASE WHEN rn = 1 THEN o2_device ELSE NULL END) AS o2_delivery_device_1\n    , MAX(CASE WHEN rn = 2 THEN o2_device ELSE NULL END) AS o2_delivery_device_2\n    , MAX(CASE WHEN rn = 3 THEN o2_device ELSE NULL END) AS o2_delivery_device_3\n    , MAX(CASE WHEN rn = 4 THEN o2_device ELSE NULL END) AS o2_delivery_device_4\nFROM stg\nGROUP BY subject_id, charttime\n;\n-- jing add tail\nalter table mimic4.measurement_oxygen_delivery\nowner to postgres;"
rhythm <- "set search_path to mimic4;\ndrop materialized view if exists measurement_rhythm;\ncreate materialized view mimic4.measurement_rhythm\ntablespace pg_default\nas\n-- jing add head\n-- Heart rhythm related documentation\nselect \n    ce.subject_id\n  , ce.charttime\n  , MAX(case when itemid = 220048 THEN value ELSE NULL END) AS heart_rhythm\n  , MAX(case when itemid = 224650 THEN value ELSE NULL END) AS ectopy_type\n  , MAX(case when itemid = 224651 THEN value ELSE NULL END) AS ectopy_frequency\n  , MAX(case when itemid = 226479 THEN value ELSE NULL END) AS ectopy_type_secondary\n  , MAX(case when itemid = 226480 THEN value ELSE NULL END) AS ectopy_frequency_secondary\nFROM chartevents ce\nwhere ce.stay_id IS NOT NULL\nand ce.itemid in\n(\n220048, -- Heart rhythm\n224650, -- Ectopy Type 1\n224651, -- Ectopy Frequency 1\n226479, -- Ectopy Type 2\n226480  -- Ectopy Frequency 2\n)\nGROUP BY ce.subject_id, ce.charttime\n;\n-- jing add tail\nalter table mimic4.measurement_rhythm\nowner to postgres;"
urine_output <- "set search_path to mimic4;\ndrop materialized view if exists measurement_urine_output;\ncreate materialized view mimic4.measurement_urine_output\ntablespace pg_default\nas\n-- jing add head\nselect\n  stay_id\n  , charttime\n  , sum(urineoutput) as urineoutput\nfrom\n(\n    select\n    -- patient identifiers\n    oe.stay_id\n    , oe.charttime\n    -- volumes associated with urine output ITEMIDs\n    -- note we consider input of GU irrigant as a negative volume\n    -- GU irrigant volume in usually has a corresponding volume out\n    -- so the net is often 0, despite large irrigant volumes\n    , case\n        when oe.itemid = 227488 and oe.value > 0 then -1*oe.value\n        else oe.value\n    end as urineoutput\n    from outputevents oe\n    where itemid in\n    (\n    226559, -- Foley\n    226560, -- Void\n    226561, -- Condom Cath\n    226584, -- Ileoconduit\n    226563, -- Suprapubic\n    226564, -- R Nephrostomy\n    226565, -- L Nephrostomy\n    226567, -- Straight Cath\n    226557, -- R Ureteral Stent\n    226558, -- L Ureteral Stent\n    227488, -- GU Irrigant Volume In\n    227489  -- GU Irrigant/Urine Volume Out\n    )\n) uo\ngroup by stay_id, charttime\n;\n-- jing add tail\nalter table mimic4.measurement_urine_output\nowner to postgres;"
urine_output_rate <- "set search_path to mimic4;\ndrop materialized view if exists measurement_urine_output_rate;\ncreate materialized view mimic4.measurement_urine_output_rate\ntablespace pg_default\nas\n-- jing add head\n-- attempt to calculate urine output per hour\n-- rate/hour is the interpretable measure of kidney function\n-- though it is difficult to estimate from aperiodic point measures\n-- first we get the earliest heart rate documented for the stay\nWITH tm AS\n(\n    SELECT ie.stay_id\n      , min(charttime) AS intime_hr\n      , max(charttime) AS outtime_hr\n    FROM icustays ie\n    INNER JOIN chartevents ce\n      ON ie.stay_id = ce.stay_id\n      AND ce.itemid = 220045\n      AND ce.charttime > DATETIME_SUB(ie.intime, interval '1 MONTH' * (1))\n      AND ce.charttime < DATETIME_ADD(ie.outtime, interval '1 MONTH' * (1))\n    GROUP BY ie.stay_id\n)\n-- now calculate time since last UO measurement\n, uo_tm AS\n(\n    SELECT tm.stay_id\n    , CASE\n        WHEN LAG(charttime) OVER W IS NULL\n        THEN datetime_diff(charttime, intime_hr, 'MINUTE')\n    ELSE datetime_diff(charttime, LAG(charttime) OVER W, 'MINUTE')\n    END AS tm_since_last_uo\n    , uo.charttime\n    , uo.urineoutput\n    FROM tm\n    INNER JOIN measurement_urine_output uo\n        ON tm.stay_id = uo.stay_id\n    WINDOW W AS (PARTITION BY tm.stay_id ORDER BY charttime)\n)\n, ur_stg as\n(\n  select io.stay_id, io.charttime\n  -- we have joined each row to all rows preceding within 24 hours\n  -- we can now sum these rows to get total UO over the last 24 hours\n  -- we can use case statements to restrict it to only the last 6/12 hours\n  -- therefore we have three sums:\n  -- 1) over a 6 hour period\n  -- 2) over a 12 hour period\n  -- 3) over a 24 hour period\n  , SUM(DISTINCT io.urineoutput) AS uo\n  -- note that we assume data charted at charttime corresponds to 1 hour of UO\n  -- therefore we use '5' and '11' to restrict the period, rather than 6/12\n  -- this assumption may overestimate UO rate when documentation is done less than hourly\n  , sum(case when datetime_diff(io.charttime, iosum.charttime, 'HOUR') <= 5\n      then iosum.urineoutput\n    else null end) as urineoutput_6hr\n  , SUM(CASE WHEN datetime_diff(io.charttime, iosum.charttime, 'HOUR') <= 5\n        THEN iosum.tm_since_last_uo\n    ELSE NULL END)/60.0 AS uo_tm_6hr\n  , sum(case when datetime_diff(io.charttime, iosum.charttime, 'HOUR') <= 11\n      then iosum.urineoutput\n    else null end) as urineoutput_12hr\n  , SUM(CASE WHEN datetime_diff(io.charttime, iosum.charttime, 'HOUR') <= 11\n        THEN iosum.tm_since_last_uo\n    ELSE NULL END)/60.0 AS uo_tm_12hr\n
    -- 24 hours\n  , sum(iosum.urineoutput) as urineoutput_24hr\n  , SUM(iosum.tm_since_last_uo)/60.0 AS uo_tm_24hr\n\n  from uo_tm io\n  -- this join gives you all UO measurements over a 24 hour period\n  left join uo_tm iosum\n    on  io.stay_id = iosum.stay_id\n    and io.charttime >= iosum.charttime\n    and io.charttime <= (DATETIME_ADD(iosum.charttime, interval '1 HOUR' * ('23')))\n  group by io.stay_id, io.charttime\n)\nselect\n  ur.stay_id\n, ur.charttime\n, wd.weight\n, ur.uo\n, ur.urineoutput_6hr\n, ur.urineoutput_12hr\n, ur.urineoutput_24hr\n, CASE WHEN uo_tm_6hr >= 6 THEN ROUND(CAST((ur.urineoutput_6hr/wd.weight/uo_tm_6hr) AS NUMERIC), 4) END AS uo_mlkghr_6hr\n, CASE WHEN uo_tm_12hr >= 12 THEN ROUND(CAST((ur.urineoutput_12hr/wd.weight/uo_tm_12hr) AS NUMERIC), 4) END AS uo_mlkghr_12hr\n, CASE WHEN uo_tm_24hr >= 24 THEN ROUND(CAST((ur.urineoutput_24hr/wd.weight/uo_tm_24hr) AS NUMERIC), 4) END AS uo_mlkghr_24hr\n-- time of earliest UO measurement that was used to calculate the rate\n, ROUND(uo_tm_6hr, 2) AS uo_tm_6hr\n, ROUND(uo_tm_12hr, 2) AS uo_tm_12hr\n, ROUND(uo_tm_24hr, 2) AS uo_tm_24hr\nfrom ur_stg ur\nLEFT JOIN durations_weight_durations wd\n    ON ur.stay_id = wd.stay_id\n    AND ur.charttime > wd.starttime\n    AND ur.charttime <= wd.endtime\n    AND wd.weight > 0\n;\n-- jing add tail\nalter table mimic4.measurement_urine_output_rate\nowner to postgres;"
ventilator_setting <- "set search_path to mimic4;\ndrop materialized view if exists measurement_ventilator_setting;\ncreate materialized view mimic4.measurement_ventilator_setting\ntablespace pg_default\nas\n-- jing add head\nwith ce as\n(\n  SELECT\n      ce.subject_id\n    , ce.stay_id\n    , ce.charttime\n    , itemid\n    -- TODO: clean\n    , value\n    , case\n        -- begin fio2 cleaning\n        when itemid = 223835\n        then\n            case\n                when valuenum >= 0.20 and valuenum <= 1\n                    then valuenum * 100\n                -- improperly input data - looks like O2 flow in litres\n                when valuenum > 1 and valuenum < 20\n                    then null\n                when valuenum >= 20 and valuenum <= 100\n                    then valuenum\n            ELSE NULL END\n        -- end of fio2 cleaning\n        -- begin peep cleaning\n        WHEN itemid in (220339, 224700)\n        THEN\n          CASE\n            WHEN valuenum > 100 THEN NULL\n            WHEN valuenum < 0 THEN NULL\n          ELSE valuenum END\n        -- end peep cleaning\n    ELSE valuenum END AS valuenum\n    , valueuom\n    , storetime\n  FROM chartevents ce\n  where ce.value IS NOT NULL\n  AND ce.stay_id IS NOT NULL\n  AND ce.itemid IN\n  (\n      224688 -- Respiratory Rate (Set)\n    , 224689 -- Respiratory Rate (spontaneous)\n    , 224690 -- Respiratory Rate (Total)\n    , 224687 -- minute volume\n    , 224685, 224684, 224686 -- tidal volume\n    , 224696 -- PlateauPressure\n    , 220339, 224700 -- PEEP\n    , 223835 -- fio2\n    , 223849 -- vent mode\n    , 229314 -- vent mode (Hamilton)\n    , 223848 -- vent type\n  )\n)\nSELECT\n      subject_id\n    , MAX(stay_id) AS stay_id\n    , charttime\n    , MAX(CASE WHEN itemid = 224688 THEN valuenum ELSE NULL END) AS respiratory_rate_set\n    , MAX(CASE WHEN itemid = 224690 THEN valuenum ELSE NULL END) AS respiratory_rate_total\n    , MAX(CASE WHEN itemid = 224689 THEN valuenum ELSE NULL END) AS respiratory_rate_spontaneous\n    , MAX(CASE WHEN itemid = 224687 THEN valuenum ELSE NULL END) AS minute_volume\n    , MAX(CASE WHEN itemid = 224684 THEN valuenum ELSE NULL END) AS tidal_volume_set\n    , MAX(CASE WHEN itemid = 224685 THEN valuenum ELSE NULL END) AS tidal_volume_observed\n    , MAX(CASE WHEN itemid = 224686 THEN valuenum ELSE NULL END) AS tidal_volume_spontaneous\n    , MAX(CASE WHEN itemid = 224696 THEN valuenum ELSE NULL END) AS plateau_pressure\n    , MAX(CASE WHEN itemid in (220339, 224700) THEN valuenum ELSE NULL END) AS peep\n    , MAX(CASE WHEN itemid = 223835 THEN valuenum ELSE NULL END) AS fio2\n    , MAX(CASE WHEN itemid = 223849 THEN value ELSE NULL END) AS ventilator_mode\n    , MAX(CASE WHEN itemid = 229314 THEN value ELSE NULL END) AS ventilator_mode_hamilton\n    , MAX(CASE WHEN itemid = 223848 THEN value ELSE NULL END) AS ventilator_type\nFROM ce\nGROUP BY subject_id, charttime\n;\n-- jing add tail\nalter table mimic4.measurement_ventilator_setting\nowner to postgres;"
vitalsign <- "set search_path to mimic4;\ndrop materialized view if exists measurement_vitalsign;\ncreate materialized view mimic4.measurement_vitalsign\ntablespace pg_default\nas\n-- jing add head\n-- This query pivots the vital signs for the entire patient stay.\n-- Vital signs include heart rate, blood pressure, respiration rate, and temperature\nselect\n    ce.subject_id\n  , ce.stay_id\n  , ce.charttime\n  , AVG(case when itemid in (220045) and valuenum > 0 and valuenum < 300 then valuenum else null end) as heart_rate\n  , AVG(case when itemid in (220179,220050) and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp\n  , AVG(case when itemid in (220180,220051) and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp\n  , AVG(case when itemid in (220052,220181,225312) and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp\n  , AVG(case when itemid = 220179 and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp_ni\n  , AVG(case when itemid = 220180 and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp_ni\n  , AVG(case when itemid = 220181 and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp_ni\n  , AVG(case when itemid in (220210,224690) and valuenum > 0 and valuenum < 70 then valuenum else null end) as resp_rate\n  , ROUND(cast(\n      \tAVG(case when itemid in (223761) and valuenum > 70 and valuenum < 120 then (valuenum-32)/1.8 -- converted to degC in valuenum call\n              \twhen itemid in (223762) and valuenum > 10 and valuenum < 50  then valuenum else null end)\n\t  as numeric)\n    , 2) as temperature\n  , MAX(CASE WHEN itemid = 224642 THEN value ELSE NULL END) AS temperature_site\n  , AVG(case when itemid in (220277) and valuenum > 0 and valuenum <= 100 then valuenum else null end) as spo2\n  , AVG(case when itemid in (225664,220621,226537) and valuenum > 0 then valuenum else null end) as glucose\n  FROM chartevents ce\n  where ce.stay_id IS NOT NULL\n  and ce.itemid in\n  (\n    220045, -- Heart Rate\n    225309, -- ART BP Systolic\n    225310, -- ART BP Diastolic\n    225312, -- ART BP Mean\n    220050, -- Arterial Blood Pressure systolic\n    220051, -- Arterial Blood Pressure diastolic\n    220052, -- Arterial Blood Pressure mean\n    220179, -- Non Invasive Blood Pressure systolic\n    220180, -- Non Invasive Blood Pressure diastolic\n    220181, -- Non Invasive Blood Pressure mean\n    220210, -- Respiratory Rate\n    224690, -- Respiratory Rate (Total)\n    220277, -- SPO2, peripheral\n    -- GLUCOSE, both lab and fingerstick\n    225664, -- Glucose finger stick\n    220621, -- Glucose (serum)\n    226537, -- Glucose (whole blood)\n    -- TEMPERATURE\n    223762, -- \\\"Temperature Celsius\\\"\n    223761,  -- \\\"Temperature Fahrenheit\\\"\n    224642 -- Temperature Site\n    -- 226329 -- Blood Temperature CCO (C)\n)\ngroup by ce.subject_id, ce.stay_id, ce.charttime\n;\n-- jing add tail\nalter table mimic4.measurement_vitalsign\nowner to postgres;"

# medication 8 - 0
antibiotic <- "set search_path to mimic4;\ndrop materialized view if exists medication_antibiotic;\ncreate materialized view mimic4.medication_antibiotic\ntablespace pg_default\nas\n-- jing add head\nwith abx as\n(\n  SELECT DISTINCT\n    drug\n    , route\n    , case\n\t-- when \n      when lower(drug) like '%adoxa%' then 1\n      when lower(drug) like '%ala-tet%' then 1\n      when lower(drug) like '%alodox%' then 1\n      when lower(drug) like '%amikacin%' then 1\n      when lower(drug) like '%amikin%' then 1\n      when lower(drug) like '%amoxicill%' then 1\n      when lower(drug) like '%amphotericin%' then 1\n      when lower(drug) like '%anidulafungin%' then 1\n      when lower(drug) like '%ancef%' then 1\n      when lower(drug) like '%clavulanate%' then 1\n      when lower(drug) like '%ampicillin%' then 1\n      when lower(drug) like '%augmentin%' then 1\n      when lower(drug) like '%avelox%' then 1\n      when lower(drug) like '%avidoxy%' then 1\n      when lower(drug) like '%azactam%' then 1\n      when lower(drug) like '%azithromycin%' then 1\n      when lower(drug) like '%aztreonam%' then 1\n      when lower(drug) like '%axetil%' then 1\n      when lower(drug) like '%bactocill%' then 1\n      when lower(drug) like '%bactrim%' then 1\n      when lower(drug) like '%bactroban%' then 1\n      when lower(drug) like '%bethkis%' then 1\n      when lower(drug) like '%biaxin%' then 1\n      when lower(drug) like '%bicillin l-a%' then 1\n      when lower(drug) like '%cayston%' then 1\n      when lower(drug) like '%cefazolin%' then 1\n      when lower(drug) like '%cedax%' then 1\n      when lower(drug) like '%cefoxitin%' then 1\n      when lower(drug) like '%ceftazidime%' then 1\n      when lower(drug) like '%cefaclor%' then 1\n      when lower(drug) like '%cefadroxil%' then 1\n      when lower(drug) like '%cefdinir%' then 1\n      when lower(drug) like '%cefditoren%' then 1\n      when lower(drug) like '%cefepime%' then 1\n      when lower(drug) like '%cefotan%' then 1\n      when lower(drug) like '%cefotetan%' then 1\n      when lower(drug) like '%cefotaxime%' then 1\n      when lower(drug) like '%ceftaroline%' then 1\n      when lower(drug) like '%cefpodoxime%' then 1\n      when lower(drug) like '%cefpirome%' then 1\n      when lower(drug) like '%cefprozil%' then 1\n      when lower(drug) like '%ceftibuten%' then 1\n      when lower(drug) like '%ceftin%' then 1\n      when lower(drug) like '%ceftriaxone%' then 1\n      when lower(drug) like '%cefuroxime%' then 1\n      when lower(drug) like '%cephalexin%' then 1\n      when lower(drug) like '%cephalothin%' then 1\n      when lower(drug) like '%cephapririn%' then 1\n      when lower(drug) like '%chloramphenicol%' then 1\n      when lower(drug) like '%cipro%' then 1\n\t
    -- whenw\n      when lower(drug) like '%ciprofloxacin%' then 1\n      when lower(drug) like '%claforan%' then 1\n      when lower(drug) like '%clarithromycin%' then 1\n      when lower(drug) like '%cleocin%' then 1\n      when lower(drug) like '%clindamycin%' then 1\n      when lower(drug) like '%cubicin%' then 1\n      when lower(drug) like '%dicloxacillin%' then 1\n      when lower(drug) like '%dirithromycin%' then 1\n      when lower(drug) like '%doryx%' then 1\n      when lower(drug) like '%doxycy%' then 1\n      when lower(drug) like '%duricef%' then 1\n      when lower(drug) like '%dynacin%' then 1\n      when lower(drug) like '%ery-tab%' then 1\n      when lower(drug) like '%eryped%' then 1\n      when lower(drug) like '%eryc%' then 1\n      when lower(drug) like '%erythrocin%' then 1\n      when lower(drug) like '%erythromycin%' then 1\n      when lower(drug) like '%factive%' then 1\n      when lower(drug) like '%flagyl%' then 1\n      when lower(drug) like '%fortaz%' then 1\n      when lower(drug) like '%furadantin%' then 1\n      when lower(drug) like '%garamycin%' then 1\n      when lower(drug) like '%gentamicin%' then 1\n      when lower(drug) like '%kanamycin%' then 1\n      when lower(drug) like '%keflex%' then 1\n      when lower(drug) like '%kefzol%' then 1\n      when lower(drug) like '%ketek%' then 1\n      when lower(drug) like '%levaquin%' then 1\n      when lower(drug) like '%levofloxacin%' then 1\n      when lower(drug) like '%lincocin%' then 1\n      when lower(drug) like '%linezolid%' then 1\n      when lower(drug) like '%macrobid%' then 1\n      when lower(drug) like '%macrodantin%' then 1\n      when lower(drug) like '%maxipime%' then 1\n      when lower(drug) like '%mefoxin%' then 1\n      when lower(drug) like '%metronidazole%' then 1\n      when lower(drug) like '%meropenem%' then 1\n      when lower(drug) like '%methicillin%' then 1\n      when lower(drug) like '%minocin%' then 1\n      when lower(drug) like '%minocycline%' then 1\n      when lower(drug) like '%monodox%' then 1\n      when lower(drug) like '%monurol%' then 1\n      when lower(drug) like '%morgidox%' then 1\n      when lower(drug) like '%moxatag%' then 1\n      when lower(drug) like '%moxifloxacin%' then 1\n      when lower(drug) like '%mupirocin%' then 1\n      when lower(drug) like '%myrac%' then 1\n\t-- when2\n      when lower(drug) like '%nafcillin%' then 1\n      when lower(drug) like '%neomycin%' then 1\n      when lower(drug) like '%nicazel doxy 30%' then 1\n      when lower(drug) like '%nitrofurantoin%' then 1\n      when lower(drug) like '%norfloxacin%' then 1\n      when lower(drug) like '%noroxin%' then 1\n      when lower(drug) like '%ocudox%' then 1\n      when lower(drug) like '%ofloxacin%' then 1\n      when lower(drug) like '%omnicef%' then 1\n      when lower(drug) like '%oracea%' then 1\n      when lower(drug) like '%oraxyl%' then 1\n\t
    -- when1\n      when lower(drug) like '%oxacillin%' then 1\n      when lower(drug) like '%pc pen vk%' then 1\n      when lower(drug) like '%pce dispertab%' then 1\n      when lower(drug) like '%panixine%' then 1\n      when lower(drug) like '%pediazole%' then 1\n      when lower(drug) like '%penicillin%' then 1\n      when lower(drug) like '%periostat%' then 1\n      when lower(drug) like '%pfizerpen%' then 1\n      when lower(drug) like '%piperacillin%' then 1\n      when lower(drug) like '%tazobactam%' then 1\n      when lower(drug) like '%primsol%' then 1\n      when lower(drug) like '%proquin%' then 1\n      when lower(drug) like '%raniclor%' then 1\n      when lower(drug) like '%rifadin%' then 1\n      when lower(drug) like '%rifampin%' then 1\n      when lower(drug) like '%rocephin%' then 1\n      when lower(drug) like '%smz-tmp%' then 1\n      when lower(drug) like '%septra%' then 1\n      when lower(drug) like '%septra ds%' then 1\n      when lower(drug) like '%septra%' then 1\n      when lower(drug) like '%solodyn%' then 1\n      when lower(drug) like '%spectracef%' then 1\n      when lower(drug) like '%streptomycin%' then 1\n      when lower(drug) like '%sulfadiazine%' then 1\n      when lower(drug) like '%sulfamethoxazole%' then 1\n      when lower(drug) like '%trimethoprim%' then 1\n      when lower(drug) like '%sulfatrim%' then 1\n      when lower(drug) like '%sulfisoxazole%' then 1\n      when lower(drug) like '%suprax%' then 1\n      when lower(drug) like '%synercid%' then 1\n      when lower(drug) like '%tazicef%' then 1\n      when lower(drug) like '%tetracycline%' then 1\n      when lower(drug) like '%timentin%' then 1\n      when lower(drug) like '%tobramycin%' then 1\n      when lower(drug) like '%trimethoprim%' then 1\n      when lower(drug) like '%unasyn%' then 1\n      when lower(drug) like '%vancocin%' then 1\n      when lower(drug) like '%vancomycin%' then 1\n      when lower(drug) like '%vantin%' then 1\n      when lower(drug) like '%vibativ%' then 1\n      when lower(drug) like '%vibra-tabs%' then 1\n      when lower(drug) like '%vibramycin%' then 1\n      when lower(drug) like '%zinacef%' then 1\n      when lower(drug) like '%zithromax%' then 1\n      when lower(drug) like '%zosyn%' then 1\n      when lower(drug) like '%zyvox%' then 1\n\t-- when3\n    else 0\n    end as antibiotic\n  from prescriptions\n  -- excludes vials/syringe/normal saline, etc\n  where drug_type not in ('BASE')\n  -- we exclude routes via the eye, ears, or topically\n  and route not in ('OU','OS','OD','AU','AS','AD', 'TP')\n  and lower(route) not like '%ear%'\n  and lower(route) not like '%eye%'\n  -- we exclude certain types of antibiotics: topical creams, gels, desens, etc\n  and lower(drug) not like '%cream%'\n  and lower(drug) not like '%desensitization%'\n  and lower(drug) not like '%ophth oint%'\n  and lower(drug) not like '%gel%'\n  -- other routes not sure about...\n  -- for sure keep: ('IV','PO','PO/NG','ORAL', 'IV DRIP', 'IV BOLUS')\n  -- ? VT, PB, PR, PL, NS, NG, NEB, NAS, LOCK, J TUBE, IVT\n  -- ? IT, IRR, IP, IO, INHALATION, IN, IM\n  -- ? IJ, IH, G TUBE, DIALYS\n  -- ?? enemas??\n)\nselect \npr.subject_id, pr.hadm_id\n, ie.stay_id\n, pr.drug as antibiotic\n, pr.route\n, pr.starttime\n, pr.stoptime\nfrom prescriptions pr\n-- inner join to subselect to only antibiotic prescriptions\ninner join abx\n    on pr.drug = abx.drug\n    -- route is never NULL for antibiotics\n    -- only ~4000 null rows in prescriptions total.\n    AND pr.route = abx.route\n-- add in stay_id as we use this table for sepsis-3\nLEFT JOIN icustays ie\n    ON pr.hadm_id = ie.hadm_id\n    AND pr.starttime >= ie.intime\n    AND pr.starttime < ie.outtime\nWHERE abx.antibiotic = 1\n;\n-- jing add tail\nalter table mimic4.medication_antibiotic\nowner to postgres;"
dobutamine <- "set search_path to mimic4;\ndrop materialized view if exists medication_dobutamine;\ncreate materialized view mimic4.medication_dobutamine\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of dopamine administration\nselect\nstay_id, linkorderid\n, rate as vaso_rate\n, amount as vaso_amount\n, starttime\n, endtime\nfrom inputevents\nwhere itemid = 221653;\n-- dobutamine;\n-- jing add tail\nalter table mimic4.medication_dobutamine\nowner to postgres;"
dopamine <- "set search_path to mimic4;\ndrop materialized view if exists medication_dopamine;\ncreate materialized view mimic4.medication_dopamine\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of dopamine administration\nselect\nstay_id, linkorderid\n, rate as vaso_rate\n, amount as vaso_amount\n, starttime\n, endtime\nfrom inputevents\nwhere itemid = 221662;\n-- dopamine;\n-- jing add tail\nalter table mimic4.medication_dopamine\nowner to postgres;"
epinephrine <- "set search_path to mimic4;\ndrop materialized view if exists medication_epinephrine;\ncreate materialized view mimic4.medication_epinephrine\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of epinephrine administration\nselect\nstay_id, linkorderid\n, rate as vaso_rate\n, amount as vaso_amount\n, starttime\n, endtime\nfrom inputevents\nwhere itemid = 221289;\n-- epinephrine;\n-- jing add tail\nalter table mimic4.medication_epinephrine\nowner to postgres;"
neuroblock <- "set search_path to mimic4;\ndrop materialized view if exists medication_neuroblock;\ncreate materialized view mimic4.medication_neuroblock\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of neuromuscular blocking agents\nselect\n    stay_id, orderid\n  , rate as drug_rate\n  , amount as drug_amount\n  , starttime\n  , endtime\nfrom inputevents\nwhere itemid in\n(\n    222062 -- Vecuronium (664 rows, 154 infusion rows)\n  , 221555 -- Cisatracurium (9334 rows, 8970 infusion rows)\n)\nand rate is not null;\n-- only continuous infusions;\n-- jing add tail\nalter table mimic4.medication_neuroblock\nowner to postgres;"
norepinephrine <- "set search_path to mimic4;\ndrop materialized view if exists medication_norepinephrine;\ncreate materialized view mimic4.medication_norepinephrine\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of norepinephrine administration\nselect\n  stay_id, linkorderid\n  , rate as vaso_rate\n  , amount as vaso_amount\n  , starttime\n  , endtime\nfrom inputevents\nwhere itemid = 221906;\n-- norepinephrine;\n-- jing add tail\nalter table mimic4.medication_norepinephrine\nowner to postgres;"
phenylephrine <- "set search_path to mimic4;\ndrop materialized view if exists medication_phenylephrine;\ncreate materialized view mimic4.medication_phenylephrine\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of phenylephrine administration\nselect\n  stay_id, linkorderid\n  , rate as vaso_rate\n  , amount as vaso_amount\n  , starttime\n  , endtime\nfrom inputevents\nwhere itemid = 221749;\n-- phenylephrine;\n-- jing add tail\nalter table mimic4.medication_phenylephrine\nowner to postgres;"
vasopressin <- "set search_path to mimic4;\ndrop materialized view if exists medication_vasopressin;\ncreate materialized view mimic4.medication_vasopressin\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts dose+durations of vasopressin administration\nselect\n  stay_id, linkorderid\n  , rate as vaso_rate\n  , amount as vaso_amount\n  , starttime\n  , endtime\nfrom inputevents\nwhere itemid = 222315;\n-- vasopressin;\n-- jing add tail\nalter table mimic4.medication_vasopressin\nowner to postgres;"



# treatment - 0
crrt <- "set search_path to mimic4;\ndrop materialized view if exists treatment_crrt;\ncreate materialized view mimic4.treatment_crrt\ntablespace pg_default\nas\n-- jing add head\nwith crrt_settings as\n(\n  select ce.stay_id, ce.charttime\n  , CASE WHEN ce.itemid = 227290 THEN ce.value END AS crrt_mode\n  , CASE WHEN ce.itemid = 224149 THEN ce.valuenum ELSE NULL END AS AccessPressure\n  , CASE WHEN ce.itemid = 224144 THEN ce.valuenum ELSE NULL END AS BloodFlow -- (ml/min)\n  , CASE WHEN ce.itemid = 228004 THEN ce.valuenum ELSE NULL END AS Citrate -- (ACD-A)\n  , CASE WHEN ce.itemid = 225183 THEN ce.valuenum ELSE NULL END AS CurrentGoal\n  , CASE WHEN ce.itemid = 225977 THEN ce.value ELSE NULL END AS DialysateFluid\n  , CASE WHEN ce.itemid = 224154 THEN ce.valuenum ELSE NULL END AS DialysateRate\n  , CASE WHEN ce.itemid = 224151 THEN ce.valuenum ELSE NULL END AS EffluentPressure\n  , CASE WHEN ce.itemid = 224150 THEN ce.valuenum ELSE NULL END AS FilterPressure\n  , CASE WHEN ce.itemid = 225958 THEN ce.value ELSE NULL END AS HeparinConcentration -- (units/mL)\n  , CASE WHEN ce.itemid = 224145 THEN ce.valuenum ELSE NULL END AS HeparinDose -- (per hour)\n  -- below may not account for drug infusion/hyperalimentation/anticoagulants infused\n  , CASE WHEN ce.itemid = 224191 THEN ce.valuenum ELSE NULL END AS HourlyPatientFluidRemoval\n  , CASE WHEN ce.itemid = 228005 THEN ce.valuenum ELSE NULL END AS PrefilterReplacementRate\n  , CASE WHEN ce.itemid = 228006 THEN ce.valuenum ELSE NULL END AS PostFilterReplacementRate\n  , CASE WHEN ce.itemid = 225976 THEN ce.value ELSE NULL END AS ReplacementFluid\n  , CASE WHEN ce.itemid = 224153 THEN ce.valuenum ELSE NULL END AS ReplacementRate\n  , CASE WHEN ce.itemid = 224152 THEN ce.valuenum ELSE NULL END AS ReturnPressure\n  , CASE WHEN ce.itemid = 226457 THEN ce.valuenum END AS UltrafiltrateOutput\n  -- separate system integrity into sub components\n  -- need to do this as 224146 has multiple unique values for a single charttime\n  -- e.g. \\\"Clots Present\\\" and \\\"Active\\\" at same time\n  , CASE\n        WHEN ce.itemid = 224146\n        AND ce.value IN ('Active', 'Initiated', 'Reinitiated', 'New Filter')\n            THEN 1\n        WHEN ce.itemid = 224146\n        AND ce.value IN ('Recirculating', 'Discontinued')\n            THEN 0\n    ELSE NULL END as system_active\n  , CASE\n        WHEN ce.itemid = 224146\n        AND ce.value IN ('Clots Present', 'Clots Present')\n            THEN 1\n        WHEN ce.itemid = 224146\n        AND ce.value IN ('No Clot Present', 'No Clot Present')\n            THEN 0\n    ELSE NULL END as clots\n  , CASE \n        WHEN ce.itemid = 224146\n        AND ce.value IN ('Clots Increasing', 'Clot Increasing')\n            THEN 1\n    ELSE NULL END as clots_increasing\n  , CASE\n        WHEN ce.itemid = 224146\n        AND ce.value IN ('Clotted')\n            THEN 1\n    ELSE NULL END as clotted\n  from chartevents ce\n  where ce.itemid in\n  (\n
    -- MetaVision ITEMIDs\n    227290, -- crrt Mode\n    224146, -- System Integrity\n    -- 225956,  -- Reason for crrt Filter Change\n    -- above itemid is one of: Clotted, Line Changed, Procedure\n    -- only ~200 rows, not super useful\n    224149, -- Access Pressure\n    224144, -- Blood Flow (ml/min)\n    228004, -- Citrate (ACD-A)\n    225183, -- Current Goal\n    225977, -- Dialysate Fluid\n    224154, -- Dialysate Rate\n    224151, -- Effluent Pressure\n    224150, -- Filter Pressure\n    225958, -- Heparin Concentration (units/mL)\n    224145, -- Heparin Dose (per hour)\n    224191, -- Hourly Patient Fluid Removal\n    228005, -- PBP (Prefilter) Replacement Rate\n    228006, -- Post Filter Replacement Rate\n    225976, -- Replacement Fluid\n    224153, -- Replacement Rate\n    224152, -- Return Pressure\n    226457  -- Ultrafiltrate Output\n  )\n  and ce.value is not null\n)\n-- use MAX() to collapse to a single row\n-- there is only ever 1 row for unique combinations of stay_id/charttime/itemid\nselect stay_id\n, charttime\n, MAX(crrt_mode) AS crrt_mode\n, MAX(AccessPressure) AS access_pressure\n, MAX(BloodFlow) AS blood_flow\n, MAX(Citrate) AS citrate\n, MAX(CurrentGoal) AS current_goal\n, MAX(DialysateFluid) AS dialysate_fluid\n, MAX(DialysateRate) AS dialysate_rate\n, MAX(EffluentPressure) AS effluent_pressure\n, MAX(FilterPressure) AS filter_pressure\n, MAX(HeparinConcentration) AS heparin_concentration\n, MAX(HeparinDose) AS heparin_dose\n, MAX(HourlyPatientFluidRemoval) AS hourly_patient_fluid_removal\n, MAX(PrefilterReplacementRate) AS prefilter_replacement_rate\n, MAX(PostFilterReplacementRate) AS postfilter_replacement_rate\n, MAX(ReplacementFluid) AS replacement_fluid\n, MAX(ReplacementRate) AS replacement_rate\n, MAX(ReturnPressure) AS return_pressure\n, MAX(UltrafiltrateOutput) AS ultrafiltrate_output\n, MAX(system_active) AS system_active\n, MAX(clots) AS clots\n, MAX(clots_increasing) AS clots_increasing\n, MAX(clotted) AS clotted\nfrom crrt_settings\ngroup by stay_id, charttime;\n-- jing add tail\nalter table mimic4.treatment_crrt\nowner to postgres;"
invasive_line <- "set search_path to mimic4;\ndrop materialized view if exists treatment_invasive_line;\ncreate materialized view mimic4.treatment_invasive_line\ntablespace pg_default\nas\n-- jing add head\n\n-- metavision\nWITH mv AS\n(\n    SELECT \n        stay_id\n        -- since metavision separates lines using itemid, we can use it as the line number\n        , mv.itemid AS line_number\n        , di.label AS line_type\n        , mv.location AS line_site\n        , starttime, endtime\n    FROM procedureevents mv\n    INNER JOIN d_items di\n      ON mv.itemid = di.itemid\n    WHERE mv.itemid IN\n    (\n      227719 -- AVA Line\n    , 225752 -- Arterial Line\n    , 224269 -- CCO PAC\n    , 224267 -- Cordis/Introducer\n    , 224270 -- Dialysis Catheter\n    , 224272 -- IABP line\n    , 226124 -- icp Catheter\n    , 228169 -- Impella Line\n    , 225202 -- Indwelling Port (PortaCath)\n    , 228286 -- Intraosseous Device\n    , 225204 -- Midline\n    , 224263 -- Multi Lumen\n    , 224560 -- PA Catheter\n    , 224264 -- PICC Line\n    , 225203 -- Pheresis Catheter\n    , 224273 -- Presep Catheter\n    , 225789 -- Sheath\n    , 225761 -- Sheath Insertion\n    , 228201 -- Tandem Heart Access Line\n    , 228202 -- Tandem Heart Return Line\n    , 224268 -- Trauma line\n    , 225199 -- Triple Introducer\n    , 225315 -- Tunneled (Hickman) Line\n    , 225205 -- RIC\n    )\n)\n-- as a final step, combine any similar terms together\nselect\n    stay_id\n    , CASE\n        WHEN line_type IN ('Arterial Line', 'A-Line') THEN 'Arterial'\n        WHEN line_type IN ('CCO PA Line', 'CCO PAC') THEN 'Continuous Cardiac Output PA'\n        WHEN line_type IN ('Dialysis Catheter', 'Dialysis Line') THEN 'Dialysis'\n        WHEN line_type IN ('Hickman', 'Tunneled (Hickman) Line') THEN 'Hickman'\n        WHEN line_type IN ('IABP', 'IABP line') THEN 'IABP'\n        WHEN line_type IN ('Multi Lumen', 'Multi-lumen') THEN 'Multi Lumen'\n        WHEN line_type IN ('PA Catheter', 'PA line') THEN 'PA'\n        WHEN line_type IN ('PICC Line', 'PICC line') THEN 'PICC'\n        WHEN line_type IN ('Pre-Sep Catheter', 'Presep Catheter') THEN 'Pre-Sep'\n        WHEN line_type IN ('Trauma Line', 'Trauma line') THEN 'Trauma'\n        WHEN line_type IN ('Triple Introducer', 'TripleIntroducer') THEN 'Triple Introducer'\n        WHEN line_type IN ('Portacath', 'Indwelling Port (PortaCath)') THEN 'Portacath'\n
    -- the following lines were not merged with another line:\n        -- AVA Line\n        -- Camino Bolt\n        -- Cordis/Introducer\n        -- icp Catheter\n        -- Impella Line\n        -- Intraosseous Device\n        -- Introducer\n        -- Lumbar Drain\n        -- Midline\n        -- Other/Remarks\n        -- PacerIntroducer\n        -- PermaCath\n        -- Pheresis Catheter\n        -- RIC\n        -- Sheath\n        -- Tandem Heart Access Line\n        -- Tandem Heart Return Line\n        -- Venous Access\n        -- Ventriculostomy\n    ELSE line_type END AS line_type\n    , CASE\n        WHEN line_site IN ('Left Antecub', 'Left Antecube') THEN 'Left Antecube'\n        WHEN line_site IN ('Left Axilla', 'Left Axilla.') THEN 'Left Axilla'\n        WHEN line_site IN ('Left Brachial', 'Left Brachial.') THEN 'Left Brachial'\n        WHEN line_site IN ('Left Femoral', 'Left Femoral.') THEN 'Left Femoral'\n        WHEN line_site IN ('Right Antecub', 'Right Antecube') THEN 'Right Antecube' \n        WHEN line_site IN ('Right Axilla', 'Right Axilla.') THEN 'Right Axilla' \n        WHEN line_site IN ('Right Brachial', 'Right Brachial.') THEN 'Right Brachial' \n        WHEN line_site IN ('Right Femoral', 'Right Femoral.') THEN 'Right Femoral'\n        -- the following sites were not merged with other sites:\n        -- 'Left Foot'\n        -- 'Left IJ'\n        -- 'Left Radial'\n        -- 'Left Subclavian'\n        -- 'Left Ulnar'\n        -- 'Left Upper Arm'\n        -- 'Right Foot'\n        -- 'Right IJ'\n        -- 'Right Radial'\n        -- 'Right Side Head'\n        -- 'Right Subclavian'\n        -- 'Right Ulnar'\n        -- 'Right Upper Arm'\n        -- 'Transthoracic'\n        -- 'Other/Remarks'\n    ELSE line_site END AS line_site\n    , starttime\n    , endtime\nFROM mv\nORDER BY stay_id, starttime, line_type, line_site;\n-- jing add tail\nalter table mimic4.treatment_invasive_line\nowner to postgres;"
ventilation <- "set search_path to mimic4;\ndrop materialized view if exists treatment_ventilation;\ncreate materialized view mimic4.treatment_ventilation\ntablespace pg_default\nas\n-- jing add head\n-- Calculate duration of mechanical ventilation.\n-- Some useful cases for debugging:\n--  stay_id = 30019660 has a tracheostomy placed in the ICU\n--  stay_id = 30000117 has explicit documentation of extubation\n-- classify vent settings into modes\nWITH tm AS\n(\n  SELECT stay_id, charttime\n  FROM measurement_ventilator_setting\n  UNION DISTINCT\n  SELECT stay_id, charttime\n  FROM measurement_oxygen_delivery\n)\n, vs AS\n(\n    SELECT tm.stay_id, tm.charttime\n    -- source data columns, here for debug\n    , o2_delivery_device_1\n    , COALESCE(ventilator_mode, ventilator_mode_hamilton) AS vent_mode\n    -- case statement determining the type of intervention\n    -- done in order of priority: trach > mech vent > NIV > high flow > o2\n    , CASE\n    -- tracheostomy\n    WHEN o2_delivery_device_1 IN\n    (\n        'Tracheostomy tube'\n    -- 'Trach mask ' -- 16435 observations\n    )\n        THEN 'Trach'\n    -- mechanical ventilation\n    WHEN o2_delivery_device_1 IN\n    (\n        'Endotracheal tube'\n    )\n    OR ventilator_mode IN\n    (\n        '(S) CMV',\n        'APRV',\n        'APRV/Biphasic+ApnPress',\n        'APRV/Biphasic+ApnVol',\n        'APV (cmv)',\n        'Ambient',\n        'Apnea ventilation',\n        'CMV',\n        'CMV/ASSIST',\n        'CMV/ASSIST/AutoFlow',\n        'CMV/AutoFlow',\n        'CPAP/PPS',\n        'CPAP/PSV+Apn TCPL',\n        'CPAP/PSV+ApnPres',\n        'CPAP/PSV+ApnVol',\n        'MMV',\n        'MMV/AutoFlow',\n        'MMV/PSV',\n        'MMV/PSV/AutoFlow',\n        'P-CMV',\n        'PCV+',\n        'PCV+/PSV',\n        'PCV+Assist',\n        'PRES/AC',\n        'PRVC/AC',\n        'PRVC/SIMV',\n        'PSV/SBT',\n        'SIMV',\n        'SIMV/AutoFlow',\n        'SIMV/PRES',\n        'SIMV/PSV',\n        'SIMV/PSV/AutoFlow',\n        'SIMV/VOL',\n        'SYNCHRON MASTER',\n        'SYNCHRON SLAVE',\n        'VOL/AC'\n    )\n    OR ventilator_mode_hamilton IN\n    (\n        'APRV',\n        'APV (cmv)',\n        'Ambient',\n        '(S) CMV',\n        'P-CMV',\n        'SIMV',\n        'APV (simv)',\n        'P-SIMV',\n        'VS',\n        'ASV'\n    )\n        THEN 'InvasiveVent'\n    -- NIV\n    WHEN o2_delivery_device_1 IN\n    (\n        'Bipap mask ', -- 8997 observations\n        'CPAP mask ' -- 5568 observations\n    )\n    OR ventilator_mode_hamilton IN\n    (\n        'DuoPaP',\n        'NIV',\n        'NIV-ST'\n    )\n        THEN 'NonInvasiveVent'\n    -- high flow\n    when o2_delivery_device_1 IN\n    (\n        'High flow neb', -- 10785 observations\n        'High flow nasal cannula' -- 925 observations\n    )\n        THEN 'HighFlow'\n    -- normal oxygen delivery\n    WHEN o2_delivery_device_1 in\n    (\n        'Nasal cannula', -- 153714 observations\n        'Face tent', -- 24601 observations\n        'Aerosol-cool', -- 24560 observations\n        'Non-rebreather',
    -- 5182 observations\n        'Venti mask ', -- 1947 observations\n        'Medium conc mask ', -- 1888 observations\n        'T-piece', -- 1135 observations\n        'Ultrasonic neb', -- 9 observations\n        'Vapomist', -- 3 observations\n        'Oxymizer' -- 1301 observations\n    )\n        THEN 'Oxygen'\n    -- Not categorized:\n    -- 'Other', 'None'\n    ELSE NULL END AS ventilation_status\n  FROM tm\n  LEFT JOIN measurement_ventilator_setting vs\n      ON tm.stay_id = vs.stay_id\n      AND tm.charttime = vs.charttime\n  LEFT JOIN measurement_oxygen_delivery od\n      ON tm.stay_id = od.stay_id\n      AND tm.charttime = od.charttime\n)\n, vd0 AS\n(\n    SELECT\n      stay_id, charttime\n      -- source data columns, here for debug\n      , o2_delivery_device_1\n      , vent_mode\n      -- carry over the previous charttime which had the same state\n      , LAG(charttime, 1) OVER (PARTITION BY stay_id, ventilation_status ORDER BY charttime) AS charttime_lag\n      -- bring back the next charttime, regardless of the state\n      -- this will be used as the end time for state transitions\n      , LEAD(charttime, 1) OVER w AS charttime_lead\n      , ventilation_status\n      , LAG(ventilation_status, 1) OVER w AS ventilation_status_lag\n    FROM vs\n    WHERE ventilation_status IS NOT NULL\n    WINDOW w AS (PARTITION BY stay_id ORDER BY charttime)\n)\n, vd1 as\n(\n    SELECT\n        stay_id\n        -- source data columns, here for debug\n        , o2_delivery_device_1\n        , vent_mode\n        , charttime_lag\n        , charttime\n        , charttime_lead\n        , ventilation_status\n\n        -- calculate the time since the last event\n        , datetime_diff(charttime, charttime_lag, 'MINUTE')/60 as ventduration\n\n        -- now we determine if the current ventilation status is \\\"new\\\", or continuing the previous\n        , CASE\n            -- a 14 hour gap always initiates a new event\n            WHEN datetime_diff(charttime, charttime_lag, 'HOUR') >= 14 THEN 1\n            WHEN ventilation_status_lag IS NULL THEN 1\n            -- not a new event if identical to the last row\n            WHEN ventilation_status_lag != ventilation_status THEN 1\n          ELSE 0\n          END AS new_status\n    FROM vd0\n)\n, vd2 as\n(\n    SELECT vd1.*\n    -- this results in a monotonic integer assigned to each instance of ventilation\n    , SUM(new_status) OVER (PARTITION BY stay_id ORDER BY charttime) AS vent_num\n    FROM vd1\n)\n-- create the durations for each ventilation instance\nSELECT stay_id\n  , MIN(charttime) AS starttime\n  -- for the end time of the ventilation event, the time of the *next* setting\n  -- i.e. if we go NIV -> O2, the end time of NIV is the first row with a documented O2 device\n  -- ... unless it's been over 14 hours, in which case it's the last row with a documented NIV.\n  , MAX(\n        CASE\n            WHEN charttime_lead IS NULL\n            OR datetime_diff(charttime_lead, charttime, 'HOUR') >= 14\n                THEN charttime\n        ELSE charttime_lead\n        END\n   ) AS endtime\n   -- all rows with the same vent_num will have the same ventilation_status\n   -- for efficiency, we use an aggregate here, but we could equally well group by this column\n  , MAX(ventilation_status) AS ventilation_status\nFROM vd2\nGROUP BY stay_id, vent_num\nHAVING min(charttime) != max(charttime)\n;\n
    -- jing add tail\nalter table mimic4.treatment_ventilation\nowner to postgres;"
rrt <- "set search_path to mimic4;\ndrop materialized view if exists treatment_rrt;\ncreate materialized view mimic4.treatment_rrt\ntablespace pg_default\nas\n-- jing add head\n-- Creates a table with stay_id / time / dialysis type (if present)\n\nwith ce as\n(\n  select ce.stay_id\n    , ce.charttime\n          -- when ce.itemid in (152,148,149,146,147,151,150) and value is not null then 1\n          -- when ce.itemid in (229,235,241,247,253,259,265,271) and value = 'Dialysis Line' then 1\n          -- when ce.itemid = 466 and value = 'Dialysis RN' then 1\n          -- when ce.itemid = 927 and value = 'Dialysis Solutions' then 1\n          -- when ce.itemid = 6250 and value = 'dialys' then 1\n          -- when ce.\n          -- when ce.itemid = 582 and value in ('CAVH Start','CAVH D/C','CVVHD Start','CVVHD D/C','Hemodialysis st','Hemodialysis end') then 1\n    , CASE\n        -- metavision itemids\n\n        -- checkboxes\n        WHEN ce.itemid IN\n        (\n            226118 -- | Dialysis Catheter placed in outside facility      | Access Lines - Invasive | chartevents        | Checkbox\n          , 227357 -- | Dialysis Catheter Dressing Occlusive              | Access Lines - Invasive | chartevents        | Checkbox\n          , 225725 -- | Dialysis Catheter Tip Cultured                    | Access Lines - Invasive | chartevents        | Checkbox\n        ) THEN 1\n        -- numeric data\n        WHEN ce.itemid IN\n        (\n            226499 -- | Hemodialysis Output                               | Dialysis\n          , 224154 -- | Dialysate Rate                                    | Dialysis\n          , 225810 -- | Dwell Time (Peritoneal Dialysis)                  | Dialysis\n          , 225959 -- | Medication Added Amount  #1 (Peritoneal Dialysis) | Dialysis\n          , 227639 -- | Medication Added Amount  #2 (Peritoneal Dialysis) | Dialysis\n          , 225183 -- | Current Goal                     | Dialysis\n          , 227438 -- | Volume not removed               | Dialysis\n          , 224191 -- | Hourly Patient Fluid Removal     | Dialysis\n          , 225806 -- | Volume In (PD)                   | Dialysis\n          , 225807 -- | Volume Out (PD)                  | Dialysis\n          , 228004 -- | Citrate (ACD-A)                  | Dialysis\n          , 228005 -- | PBP (Prefilter) Replacement Rate | Dialysis\n          , 228006 -- | Post Filter Replacement Rate     | Dialysis\n          , 224144 -- | Blood Flow (ml/min)              | Dialysis\n          , 224145 -- | Heparin Dose (per hour)          | Dialysis\n          , 224149 -- | Access Pressure                  | Dialysis\n          , 224150 -- | Filter Pressure                  | Dialysis\n          , 224151 -- | Effluent Pressure                | Dialysis\n          , 224152 -- | Return Pressure                  | Dialysis\n          , 224153 -- | Replacement Rate                 | Dialysis\n          , 224404 -- | ART Lumen Volume                 | Dialysis\n          , 224406 -- | VEN Lumen Volume                 | Dialysis\n          , 226457 -- | Ultrafiltrate Output             | Dialysis\n        ) THEN 1\n\n
-- text fields\n        WHEN ce.itemid IN\n        (\n            224135 -- | Dialysis Access Site | Dialysis\n          , 224139 -- | Dialysis Site Appearance | Dialysis\n          , 224146 -- | System Integrity | Dialysis\n          , 225323 -- | Dialysis Catheter Site Appear | Access Lines - Invasive\n          , 225740 -- | Dialysis Catheter Discontinued | Access Lines - Invasive\n          , 225776 -- | Dialysis Catheter Dressing Type | Access Lines - Invasive\n          , 225951 -- | Peritoneal Dialysis Fluid Appearance | Dialysis\n          , 225952 -- | Medication Added #1 (Peritoneal Dialysis) | Dialysis\n          , 225953 -- | Solution (Peritoneal Dialysis) | Dialysis\n          , 225954 -- | Dialysis Access Type | Dialysis\n          , 225956 -- | Reason for crrt Filter Change | Dialysis\n          , 225958 -- | Heparin Concentration (units/mL) | Dialysis\n          , 225961 -- | Medication Added Units #1 (Peritoneal Dialysis) | Dialysis\n          , 225963 -- | Peritoneal Dialysis Catheter Type | Dialysis\n          , 225965 -- | Peritoneal Dialysis Catheter Status | Dialysis\n          , 225976 -- | Replacement Fluid | Dialysis\n          , 225977 -- | Dialysate Fluid | Dialysis\n          , 227124 -- | Dialysis Catheter Type | Access Lines - Invasive\n          , 227290 -- | crrt mode | Dialysis\n          , 227638 -- | Medication Added #2 (Peritoneal Dialysis) | Dialysis\n          , 227640 -- | Medication Added Units #2 (Peritoneal Dialysis) | Dialysis\n          , 227753 -- | Dialysis Catheter Placement Confirmed by X-ray | Access Lines - Invasive\n        ) THEN 1\n      ELSE 0 END\n      AS dialysis_present\n    , CASE\n        WHEN ce.itemid = 225965 -- Peritoneal Dialysis Catheter Status\n          AND value = 'In use' THEN 1\n        WHEN ce.itemid IN\n        (\n            226499 -- | Hemodialysis Output              | Dialysis\n          , 224154 -- | Dialysate Rate                   | Dialysis\n          , 225183 -- | Current Goal                     | Dialysis\n          , 227438 -- | Volume not removed               | Dialysis\n          , 224191 -- | Hourly Patient Fluid Removal     | Dialysis\n          , 225806 -- | Volume In (PD)                   | Dialysis\n          , 225807 -- | Volume Out (PD)                  | Dialysis\n          , 228004 -- | Citrate (ACD-A)                  | Dialysis\n          , 228005 -- | PBP (Prefilter) Replacement Rate | Dialysis\n          , 228006 -- | Post Filter Replacement Rate     | Dialysis\n          , 224144 -- | Blood Flow (ml/min)              | Dialysis\n          , 224145 -- | Heparin Dose (per hour)          | Dialysis\n          , 224153 -- | Replacement Rate                 | Dialysis\n          , 226457 -- | Ultrafiltrate Output             | Dialysis\n        ) THEN 1\n      ELSE 0 END\n      AS dialysis_active\n    , CASE\n        -- dialysis mode\n        -- we try to set dialysis mode to one of:\n        --   CVVH\n        --   CVVHD\n        --   CVVHDF\n        --   SCUF\n        --   Peritoneal\n        --   IHD\n
-- these are the modes in itemid 227290\n        WHEN ce.itemid = 227290 THEN value\n        -- itemids which imply a certain dialysis mode\n        -- peritoneal dialysis\n        WHEN ce.itemid IN \n        (\n            225810 -- | Dwell Time (Peritoneal Dialysis) | Dialysis\n          , 225806 -- | Volume In (PD)                   | Dialysis\n          , 225807 -- | Volume Out (PD)                  | Dialysis\n          , 225810 -- | Dwell Time (Peritoneal Dialysis)                  | Dialysis\n          , 227639 -- | Medication Added Amount  #2 (Peritoneal Dialysis) | Dialysis\n          , 225959 -- | Medication Added Amount  #1 (Peritoneal Dialysis) | Dialysis\n          , 225951 -- | Peritoneal Dialysis Fluid Appearance | Dialysis\n          , 225952 -- | Medication Added #1 (Peritoneal Dialysis) | Dialysis\n          , 225961 -- | Medication Added Units #1 (Peritoneal Dialysis) | Dialysis\n          , 225953 -- | Solution (Peritoneal Dialysis) | Dialysis\n          , 225963 -- | Peritoneal Dialysis Catheter Type | Dialysis\n          , 225965 -- | Peritoneal Dialysis Catheter Status | Dialysis\n          , 227638 -- | Medication Added #2 (Peritoneal Dialysis) | Dialysis\n          , 227640 -- | Medication Added Units #2 (Peritoneal Dialysis) | Dialysis\n        )\n          THEN 'Peritoneal'\n        WHEN ce.itemid = 226499\n          THEN 'IHD'\n      ELSE NULL END as dialysis_type\n  from chartevents ce\n  WHERE ce.itemid in\n  (\n    -- === MetaVision itemids === --\n  \n    -- Checkboxes\n      226118 -- | Dialysis Catheter placed in outside facility      | Access Lines - Invasive | chartevents        | Checkbox\n    , 227357 -- | Dialysis Catheter Dressing Occlusive              | Access Lines - Invasive | chartevents        | Checkbox\n    , 225725 -- | Dialysis Catheter Tip Cultured                    | Access Lines - Invasive | chartevents        | Checkbox\n\n    -- Numeric values\n    , 226499 -- | Hemodialysis Output                               | Dialysis                | chartevents        | Numeric\n    , 224154 -- | Dialysate Rate                                    | Dialysis                | chartevents        | Numeric\n    , 225810 -- | Dwell Time (Peritoneal Dialysis)                  | Dialysis                | chartevents        | Numeric\n    , 227639 -- | Medication Added Amount  #2 (Peritoneal Dialysis) | Dialysis                | chartevents        | Numeric\n    , 225183 -- | Current Goal                     | Dialysis | chartevents        | Numeric\n    , 227438 -- | Volume not removed               | Dialysis | chartevents        | Numeric\n    , 224191 -- | Hourly Patient Fluid Removal     | Dialysis | chartevents        | Numeric\n    , 225806 -- | Volume In (PD)                   | Dialysis | chartevents        | Numeric\n    , 225807 -- | Volume Out (PD)                  | Dialysis | chartevents        | Numeric\n    , 228004 -- | Citrate (ACD-A)                  | Dialysis | chartevents        | Numeric\n    , 228005 -- | PBP (Prefilter) Replacement Rate | Dialysis | chartevents        | Numeric\n    , 228006 -- | Post Filter Replacement Rate     | Dialysis | chartevents        | Numeric\n    , 224144
-- | Blood Flow (ml/min)              | Dialysis | chartevents        | Numeric\n    , 224145 -- | Heparin Dose (per hour)          | Dialysis | chartevents        | Numeric\n    , 224149 -- | Access Pressure                  | Dialysis | chartevents        | Numeric\n    , 224150 -- | Filter Pressure                  | Dialysis | chartevents        | Numeric\n    , 224151 -- | Effluent Pressure                | Dialysis | chartevents        | Numeric\n    , 224152 -- | Return Pressure                  | Dialysis | chartevents        | Numeric\n    , 224153 -- | Replacement Rate                 | Dialysis | chartevents        | Numeric\n    , 224404 -- | ART Lumen Volume                 | Dialysis | chartevents        | Numeric\n    , 224406 -- | VEN Lumen Volume                 | Dialysis | chartevents        | Numeric\n    , 226457 -- | Ultrafiltrate Output             | Dialysis | chartevents        | Numeric\n    , 225959 -- | Medication Added Amount  #1 (Peritoneal Dialysis) | Dialysis | chartevents | Numeric\n    -- Text values\n    , 224135 -- | Dialysis Access Site | Dialysis | chartevents | Text\n    , 224139 -- | Dialysis Site Appearance | Dialysis | chartevents | Text\n    , 224146 -- | System Integrity | Dialysis | chartevents | Text\n    , 225323 -- | Dialysis Catheter Site Appear | Access Lines - Invasive | chartevents | Text\n    , 225740 -- | Dialysis Catheter Discontinued | Access Lines - Invasive | chartevents | Text\n    , 225776 -- | Dialysis Catheter Dressing Type | Access Lines - Invasive | chartevents | Text\n    , 225951 -- | Peritoneal Dialysis Fluid Appearance | Dialysis | chartevents | Text\n    , 225952 -- | Medication Added #1 (Peritoneal Dialysis) | Dialysis | chartevents | Text\n    , 225953 -- | Solution (Peritoneal Dialysis) | Dialysis | chartevents | Text\n    , 225954 -- | Dialysis Access Type | Dialysis | chartevents | Text\n    , 225956 -- | Reason for crrt Filter Change | Dialysis | chartevents | Text\n    , 225958 -- | Heparin Concentration (units/mL) | Dialysis | chartevents | Text\n    , 225961 -- | Medication Added Units #1 (Peritoneal Dialysis) | Dialysis | chartevents | Text\n    , 225963 -- | Peritoneal Dialysis Catheter Type | Dialysis | chartevents | Text\n    , 225965 -- | Peritoneal Dialysis Catheter Status | Dialysis | chartevents | Text\n    , 225976 -- | Replacement Fluid | Dialysis | chartevents | Text\n    , 225977 -- | Dialysate Fluid | Dialysis | chartevents | Text\n    , 227124 -- | Dialysis Catheter Type | Access Lines - Invasive | chartevents | Text\n    , 227290 -- | crrt mode | Dialysis | chartevents | Text\n    , 227638 -- | Medication Added #2 (Peritoneal Dialysis) | Dialysis | chartevents | Text\n    , 227640 -- | Medication Added Units #2 (Peritoneal Dialysis) | Dialysis | chartevents | Text\n    , 227753 -- | Dialysis Catheter Placement Confirmed by X-ray | Access Lines - Invasive | chartevents | Text\n  )\n  AND ce.value IS NOT NULL\n)\n-- TODO:\n--   charttime + dialysis_present + dialysis_active\n--  for inputevents_cv, outputevents\n--  for procedures_mv, left join and set the dialysis_type\n, oe as\n(\n select stay_id\n    , charttime\n    , 1 AS dialysis_present\n    , 0 AS dialysis_active\n    , NULL AS dialysis_type\n from outputevents\n where itemid in\n (\n       40386
-- hemodialysis\n )\n and value > 0 -- also ensures it's not null\n)\n, mv_ranges as\n(\n  select stay_id\n    , starttime, endtime\n    , 1 AS dialysis_present\n    , 1 AS dialysis_active\n    , 'CRRT' as dialysis_type\n  from inputevents\n  where itemid in\n  (\n      227536 --\tKCl (CRRT)\tMedications\tinputevents_mv\tSolution\n    , 227525 --\tCalcium Gluconate (CRRT)\tMedications\tinputevents_mv\tSolution\n  )\n  and amount > 0 -- also ensures it's not null\n  UNION DISTINCT\n  select stay_id\n    , starttime, endtime\n    , 1 AS dialysis_present\n    , CASE WHEN itemid NOT IN (224270, 225436) THEN 1 ELSE 0 END AS dialysis_active\n    , CASE\n        WHEN itemid = 225441 THEN 'IHD'\n        WHEN itemid = 225802 THEN 'CRRT'  -- CVVH (Continuous venovenous hemofiltration)\n        WHEN itemid = 225803 THEN 'CVVHD' -- CVVHD (Continuous venovenous hemodialysis)\n        WHEN itemid = 225805 THEN 'Peritoneal'\n        WHEN itemid = 225809 THEN 'CVVHDF' -- CVVHDF (Continuous venovenous hemodiafiltration)\n        WHEN itemid = 225955 THEN 'SCUF' -- SCUF (Slow continuous ultra filtration)\n      ELSE NULL END as dialysis_type\n  from procedureevents\n  where itemid in\n  (\n      225441 -- | Hemodialysis          | 4-Procedures              | procedureevents_mv | Process\n    , 225802 -- | Dialysis - crrt       | Dialysis                  | procedureevents_mv | Process\n    , 225803 -- | Dialysis - CVVHD      | Dialysis                  | procedureevents_mv | Process\n    , 225805 -- | Peritoneal Dialysis   | Dialysis                  | procedureevents_mv | Process\n    , 224270 -- | Dialysis Catheter     | Access Lines - Invasive   | procedureevents_mv | Process\n    , 225809 -- | Dialysis - CVVHDF     | Dialysis                  | procedureevents_mv | Process\n    , 225955 -- | Dialysis - SCUF       | Dialysis                  | procedureevents_mv | Process\n    , 225436 -- | crrt Filter Change    | Dialysis                  | procedureevents_mv | Process\n  )\n  AND value IS NOT NULL\n)\n-- union together the charttime tables; append times from mv_ranges to guarantee they exist\n, stg0 AS\n(\n  SELECT\n    stay_id, charttime, dialysis_present, dialysis_active, dialysis_type\n  FROM ce\n  WHERE dialysis_present = 1\n  UNION DISTINCT\n--   SELECT\n--     stay_id, charttime, dialysis_present, dialysis_active, dialysis_type\n--   FROM oe\n--   WHERE dialysis_present = 1\n--   UNION DISTINCT\n  SELECT\n    stay_id, starttime AS charttime, dialysis_present, dialysis_active, dialysis_type\n  FROM mv_ranges\n)\nSELECT\n    stg0.stay_id\n    , charttime\n    , COALESCE(mv.dialysis_present, stg0.dialysis_present) AS dialysis_present\n    , COALESCE(mv.dialysis_active, stg0.dialysis_active) AS dialysis_active\n    , COALESCE(mv.dialysis_type, stg0.dialysis_type) AS dialysis_type\nFROM stg0\nLEFT JOIN mv_ranges mv\n  ON stg0.stay_id = mv.stay_id\n  AND stg0.charttime >= mv.starttime\n  AND stg0.charttime <= mv.endtime;\n-- jing add tail\nalter table mimic4.treatment_rrt\nowner to postgres;"






# firstday 10 - 0
first_day_bg <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_bg;\ncreate materialized view mimic4.firstday_first_day_bg\ntablespace pg_default\nas\n-- jing add head\n-- Highest/lowest blood gas values for all blood specimens (venous/arterial/mixed)\nselect\n    ie.subject_id\n    , ie.stay_id\n    , MIN(lactate) AS lactate_min, MAX(lactate) AS lactate_max\n    , MIN(ph) AS ph_min, MAX(ph) AS ph_max\n    , MIN(so2) AS so2_min, MAX(so2) AS so2_max\n    , MIN(po2) AS po2_min, MAX(po2) AS po2_max\n    , MIN(pco2) AS pco2_min, MAX(pco2) AS pco2_max\n    , MIN(aado2) AS aado2_min, MAX(aado2) AS aado2_max\n    , MIN(aado2_calc) AS aado2_calc_min, MAX(aado2_calc) AS aado2_calc_max\n    , MIN(pao2fio2ratio) AS pao2fio2ratio_min, MAX(pao2fio2ratio) AS pao2fio2ratio_max\n    , MIN(baseexcess) AS baseexcess_min, MAX(baseexcess) AS baseexcess_max\n    , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max\n    , MIN(totalco2) AS totalco2_min, MAX(totalco2) AS totalco2_max\n    , MIN(hematocrit) AS hematocrit_min, MAX(hematocrit) AS hematocrit_max\n    , MIN(hemoglobin) AS hemoglobin_min, MAX(hemoglobin) AS hemoglobin_max\n    , MIN(carboxyhemoglobin) AS carboxyhemoglobin_min, MAX(carboxyhemoglobin) AS carboxyhemoglobin_max\n    , MIN(methemoglobin) AS methemoglobin_min, MAX(methemoglobin) AS methemoglobin_max\n    , MIN(temperature) AS temperature_min, MAX(temperature) AS temperature_max\n    , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max\n    , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max\n    , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max\n    , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max\n    , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max\nFROM icustays ie\nLEFT JOIN measurement_bg bg\n    ON ie.subject_id = bg.subject_id\n    AND bg.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND bg.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_bg\nowner to postgres;"
first_day_bg_art <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_bg_art;\ncreate materialized view mimic4.firstday_first_day_bg_art\ntablespace pg_default\nas\n-- jing add head\n-- Highest/lowest blood gas values for arterial blood specimens\nselect\n    ie.subject_id\n    , ie.stay_id\n    , MIN(lactate) AS lactate_min, MAX(lactate) AS lactate_max\n    , MIN(ph) AS ph_min, MAX(ph) AS ph_max\n    , MIN(so2) AS so2_min, MAX(so2) AS so2_max\n    , MIN(po2) AS po2_min, MAX(po2) AS po2_max\n    , MIN(pco2) AS pco2_min, MAX(pco2) AS pco2_max\n    , MIN(aado2) AS aado2_min, MAX(aado2) AS aado2_max\n    , MIN(aado2_calc) AS aado2_calc_min, MAX(aado2_calc) AS aado2_calc_max\n    , MIN(pao2fio2ratio) AS pao2fio2ratio_min, MAX(pao2fio2ratio) AS pao2fio2ratio_max\n    , MIN(baseexcess) AS baseexcess_min, MAX(baseexcess) AS baseexcess_max\n    , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max\n    , MIN(totalco2) AS totalco2_min, MAX(totalco2) AS totalco2_max\n    , MIN(hematocrit) AS hematocrit_min, MAX(hematocrit) AS hematocrit_max\n    , MIN(hemoglobin) AS hemoglobin_min, MAX(hemoglobin) AS hemoglobin_max\n    , MIN(carboxyhemoglobin) AS carboxyhemoglobin_min, MAX(carboxyhemoglobin) AS carboxyhemoglobin_max\n    , MIN(methemoglobin) AS methemoglobin_min, MAX(methemoglobin) AS methemoglobin_max\n    , MIN(temperature) AS temperature_min, MAX(temperature) AS temperature_max\n    , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max\n    , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max\n    , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max\n    , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max\n    , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max\nFROM icustays ie\nLEFT JOIN measurement_bg bg\n    ON ie.subject_id = bg.subject_id\n    AND bg.specimen_pred = 'ART.'\n    AND bg.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND bg.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_bg_art\nowner to postgres;"
first_day_gcs <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_gcs;\ncreate materialized view mimic4.firstday_first_day_gcs\ntablespace pg_default\nas\n-- jing add head\nWITH gcs_final AS\n(\n    SELECT\n        gcs.*\n        -- This sorts the data by gcs\n        -- rn = 1 is the the lowest total gcs value\n        , ROW_NUMBER () OVER\n        (\n            PARTITION BY gcs.stay_id\n            ORDER BY gcs.GCS\n        ) as gcs_seq\n    FROM measurement_gcs gcs\n)\nSELECT\n    ie.subject_id\n    , ie.stay_id\n    -- The minimum gcs is determined by the above row partition\n    -- we only join if gcs_seq = 1\n    , gcs AS gcs_min\n    , gcs_motor\n    , gcs_verbal\n    , gcs_eyes\n    , gcs_unable\nFROM icustays ie\nLEFT JOIN gcs_final gs\n    ON ie.stay_id = gs.stay_id\n    AND gs.gcs_seq = 1\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_gcs\nowner to postgres;"
first_day_height <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_height;\ncreate materialized view mimic4.firstday_first_day_height\ntablespace pg_default\nas\n-- jing add head\nWITH ce AS\n(\n    SELECT\n      c.stay_id\n      , AVG(valuenum) as height_chart\n    FROM chartevents c\n    INNER JOIN icustays ie ON\n        c.stay_id = ie.stay_id\n        AND c.charttime BETWEEN DATETIME_SUB(ie.intime, interval '1 DAY' * ('1')) AND DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    WHERE c.valuenum IS NOT NULL\n    AND c.itemid in (226730) -- height\n    AND c.valuenum != 0\n    GROUP BY c.stay_id\n)\nSELECT\n    ie.subject_id\n    , ie.stay_id\n    , ROUND(AVG(height), 2) AS height\nFROM icustays ie\nLEFT JOIN measurement_height ht\n    ON ie.stay_id = ht.stay_id\n    AND ht.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND ht.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id;\n-- jing add tail\nalter table mimic4.firstday_first_day_height\nowner to postgres;"
first_day_lab <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_lab;\ncreate materialized view mimic4.firstday_first_day_lab\ntablespace pg_default\nas\n-- jing add head\nWITH cbc AS\n(\n    SELECT\n    ie.stay_id\n    , MIN(hematocrit) as hematocrit_min\n    , MAX(hematocrit) as hematocrit_max\n    , MIN(hemoglobin) as hemoglobin_min\n    , MAX(hemoglobin) as hemoglobin_max\n    , MIN(platelet) as platelets_min\n    , MAX(platelet) as platelets_max\n    , MIN(wbc) as wbc_min\n    , MAX(wbc) as wbc_max\n    FROM icustays ie\n    LEFT JOIN measurement_complete_blood_count le\n        ON le.subject_id = ie.subject_id\n        AND le.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n        AND le.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    GROUP BY ie.stay_id\n)\n, chem AS\n(\n    SELECT\n    ie.stay_id\n    , MIN(albumin) AS albumin_min, MAX(albumin) AS albumin_max\n    , MIN(globulin) AS globulin_min, MAX(globulin) AS globulin_max\n    , MIN(total_protein) AS total_protein_min, MAX(total_protein) AS total_protein_max\n    , MIN(aniongap) AS aniongap_min, MAX(aniongap) AS aniongap_max\n    , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max\n    , MIN(bun) AS bun_min, MAX(bun) AS bun_max\n    , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max\n    , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max\n    , MIN(creatinine) AS creatinine_min, MAX(creatinine) AS creatinine_max\n    , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max\n    , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max\n    , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max\n    FROM icustays ie\n    LEFT JOIN measurement_chemistry le\n        ON le.subject_id = ie.subject_id\n        AND le.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n        AND le.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    GROUP BY ie.stay_id\n)\n, diff AS\n(\n    SELECT\n    ie.stay_id\n    , MIN(basophils_abs) AS basophils_abs_min, MAX(basophils_abs) AS basophils_abs_max\n    , MIN(eosinophils_abs) AS eosinophils_abs_min, MAX(eosinophils_abs) AS eosinophils_abs_max\n    , MIN(lymphocytes_abs) AS lymphocytes_abs_min, MAX(lymphocytes_abs) AS lymphocytes_abs_max\n    , MIN(monocytes_abs) AS monocytes_abs_min, MAX(monocytes_abs) AS monocytes_abs_max\n    , MIN(neutrophils_abs) AS neutrophils_abs_min, MAX(neutrophils_abs) AS neutrophils_abs_max\n
    -- cut\n, MIN(atypical_lymphocytes) AS atypical_lymphocytes_min, MAX(atypical_lymphocytes) AS atypical_lymphocytes_max\n    , MIN(bands) AS bands_min, MAX(bands) AS bands_max\n    , MIN(immature_granulocytes) AS immature_granulocytes_min, MAX(immature_granulocytes) AS immature_granulocytes_max\n    , MIN(metamyelocytes) AS metamyelocytes_min, MAX(metamyelocytes) AS metamyelocytes_max\n    , MIN(nrbc) AS nrbc_min, MAX(nrbc) AS nrbc_max\n    FROM icustays ie\n    LEFT JOIN measurement_blood_differential le\n        ON le.subject_id = ie.subject_id\n        AND le.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n        AND le.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    GROUP BY ie.stay_id\n)\n, coag AS\n(\n    SELECT\n    ie.stay_id\n    , MIN(d_dimer) AS d_dimer_min, MAX(d_dimer) AS d_dimer_max\n    , MIN(fibrinogen) AS fibrinogen_min, MAX(fibrinogen) AS fibrinogen_max\n    , MIN(thrombin) AS thrombin_min, MAX(thrombin) AS thrombin_max\n    , MIN(inr) AS inr_min, MAX(inr) AS inr_max\n    , MIN(pt) AS pt_min, MAX(pt) AS pt_max\n    , MIN(ptt) AS ptt_min, MAX(ptt) AS ptt_max\n    FROM icustays ie\n    LEFT JOIN measurement_coagulation le\n        ON le.subject_id = ie.subject_id\n        AND le.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n        AND le.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    GROUP BY ie.stay_id\n)\n, enz AS\n(\n    SELECT\n    ie.stay_id\n    \n    , MIN(alt) AS alt_min, MAX(alt) AS alt_max\n    , MIN(alp) AS alp_min, MAX(alp) AS alp_max\n    , MIN(ast) AS ast_min, MAX(ast) AS ast_max\n    , MIN(amylase) AS amylase_min, MAX(amylase) AS amylase_max\n    , MIN(bilirubin_total) AS bilirubin_total_min, MAX(bilirubin_total) AS bilirubin_total_max\n    , MIN(bilirubin_direct) AS bilirubin_direct_min, MAX(bilirubin_direct) AS bilirubin_direct_max\n    , MIN(bilirubin_indirect) AS bilirubin_indirect_min, MAX(bilirubin_indirect) AS bilirubin_indirect_max\n    , MIN(ck_cpk) AS ck_cpk_min, MAX(ck_cpk) AS ck_cpk_max\n    , MIN(ck_mb) AS ck_mb_min, MAX(ck_mb) AS ck_mb_max\n    , MIN(ggt) AS ggt_min, MAX(ggt) AS ggt_max\n    , MIN(ld_ldh) AS ld_ldh_min, MAX(ld_ldh) AS ld_ldh_max\n    FROM icustays ie\n    LEFT JOIN measurement_enzyme le\n        ON le.subject_id = ie.subject_id\n        AND le.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n        AND le.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n    GROUP BY ie.stay_id\n)\nSELECT\nie.subject_id\n, ie.stay_id\n
    -- complete blood count\n, hematocrit_min, hematocrit_max\n, hemoglobin_min, hemoglobin_max\n, platelets_min, platelets_max\n, wbc_min, wbc_max\n-- chemistry\n, albumin_min, albumin_max\n, globulin_min, globulin_max\n, total_protein_min, total_protein_max\n, aniongap_min, aniongap_max\n, bicarbonate_min, bicarbonate_max\n, bun_min, bun_max\n, calcium_min, calcium_max\n, chloride_min, chloride_max\n, creatinine_min, creatinine_max\n, glucose_min, glucose_max\n, sodium_min, sodium_max\n, potassium_min, potassium_max\n-- blood differential\n, basophils_abs_min,   basophils_abs_max\n, eosinophils_abs_min, eosinophils_abs_max\n, lymphocytes_abs_min, lymphocytes_abs_max\n, monocytes_abs_min,   monocytes_abs_max\n, neutrophils_abs_min, neutrophils_abs_max\n, atypical_lymphocytes_min, atypical_lymphocytes_max\n, bands_min, bands_max\n, immature_granulocytes_min, immature_granulocytes_max\n, metamyelocytes_min, metamyelocytes_max\n, nrbc_min, nrbc_max\n-- coagulation\n, d_dimer_min, d_dimer_max\n, fibrinogen_min, fibrinogen_max\n, thrombin_min, thrombin_max\n, inr_min, inr_max\n, pt_min, pt_max\n, ptt_min, ptt_max\n-- enzymes and bilirubin\n, alt_min, alt_max\n, alp_min, alp_max\n, ast_min, ast_max\n, amylase_min, amylase_max\n, bilirubin_total_min, bilirubin_total_max\n, bilirubin_direct_min, bilirubin_direct_max\n, bilirubin_indirect_min, bilirubin_indirect_max\n, ck_cpk_min, ck_cpk_max\n, ck_mb_min, ck_mb_max\n, ggt_min, ggt_max\n, ld_ldh_min, ld_ldh_max\nFROM icustays ie\nLEFT JOIN cbc\n    ON ie.stay_id = cbc.stay_id\nLEFT JOIN chem\n    ON ie.stay_id = chem.stay_id\nLEFT JOIN diff\n    ON ie.stay_id = diff.stay_id\nLEFT JOIN coag\n    ON ie.stay_id = coag.stay_id\nLEFT JOIN enz\n    ON ie.stay_id = enz.stay_id\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_lab\nowner to postgres;"
first_day_rrt <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_rrt;\ncreate materialized view mimic4.firstday_first_day_rrt\ntablespace pg_default\nas\n-- jing add head\n-- flag indicating if patients received dialysis during \n-- the first day of their ICU stay\nselect\n    ie.subject_id\n    , ie.stay_id\n    , MAX(dialysis_present) AS dialysis_present\n    , MAX(dialysis_active) AS dialysis_active\n    , STRING_AGG(DISTINCT dialysis_type, ', ') AS dialysis_type\nFROM icustays ie\nLEFT JOIN treatment_rrt rrt\n\tON ie.stay_id = rrt.stay_id\n\tAND rrt.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n\tAND rrt.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id;\n-- jing add tail\nalter table mimic4.firstday_first_day_rrt\nowner to postgres;"
first_day_urine_output <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_urine_output;\ncreate materialized view mimic4.firstday_first_day_urine_output\ntablespace pg_default\nas\n-- jing add head\n-- Total urine output over the first 24 hours in the ICU\nSELECT\n  -- patient identifiers\n  ie.subject_id\n  , ie.stay_id\n  , SUM(urineoutput) AS urineoutput\nFROM icustays ie\n-- Join to the outputevents table to get urine output\nLEFT JOIN measurement_urine_output uo\n    ON ie.stay_id = uo.stay_id\n    -- ensure the data occurs during the first day\n    AND uo.charttime >= ie.intime\n    AND uo.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id;\n-- jing add tail\nalter table mimic4.firstday_first_day_urine_output\nowner to postgres;"
first_day_vitalsign <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_vitalsign;\ncreate materialized view mimic4.firstday_first_day_vitalsign\ntablespace pg_default\nas\n-- jing add head\n-- This query pivots vital signs and aggregates them\n-- for the first 24 hours of a patient's stay.\nSELECT\nie.subject_id\n, ie.stay_id\n, MIN(heart_rate) AS heart_rate_min\n, MAX(heart_rate) AS heart_rate_max\n, AVG(heart_rate) AS heart_rate_mean\n, MIN(sbp) AS sbp_min\n, MAX(sbp) AS sbp_max\n, AVG(sbp) AS sbp_mean\n, MIN(dbp) AS dbp_min\n, MAX(dbp) AS dbp_max\n, AVG(dbp) AS dbp_mean\n, MIN(mbp) AS mbp_min\n, MAX(mbp) AS mbp_max\n, AVG(mbp) AS mbp_mean\n, MIN(resp_rate) AS resp_rate_min\n, MAX(resp_rate) AS resp_rate_max\n, AVG(resp_rate) AS resp_rate_mean\n, MIN(temperature) AS temperature_min\n, MAX(temperature) AS temperature_max\n, AVG(temperature) AS temperature_mean\n, MIN(spo2) AS spo2_min\n, MAX(spo2) AS spo2_max\n, AVG(spo2) AS spo2_mean\n, MIN(glucose) AS glucose_min\n, MAX(glucose) AS glucose_max\n, AVG(glucose) AS glucose_mean\nFROM icustays ie\nLEFT JOIN measurement_vitalsign ce\n    ON ie.stay_id = ce.stay_id\n    AND ce.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND ce.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id;\n-- jing add tail\nalter table mimic4.firstday_first_day_vitalsign\nowner to postgres;"
first_day_weight <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_weight;\ncreate materialized view mimic4.firstday_first_day_weight\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts weights for adult ICU patients on their first ICU day.\n-- It does *not* use any information after the first ICU day, as weight is\n-- sometimes used to monitor fluid balance.\n-- The MIMIC-III version used echodata but this isn't available in MIMIC-IV.\nSELECT\n  ie.subject_id\n  , ie.stay_id\n  , AVG(CASE WHEN weight_type = 'admit' THEN ce.weight ELSE NULL END) AS weight_admit\n  , AVG(ce.weight) AS weight\n  , MIN(ce.weight) AS weight_min\n  , MAX(ce.weight) AS weight_max\nFROM icustays ie\n  -- admission weight\nLEFT JOIN durations_weight_durations ce\n    ON ie.stay_id = ce.stay_id\n    -- we filter to weights documented during or before the 1st day\n    AND ce.starttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\nGROUP BY ie.subject_id, ie.stay_id\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_weight\nowner to postgres;"



# organfailure 4 - 0
kdigo_creatinine <- "set search_path to mimic4;\ndrop materialized view if exists organfailure_kdigo_creatinine;\ncreate materialized view mimic4.organfailure_kdigo_creatinine\ntablespace pg_default\nas\n-- jing add head\n-- Extract all creatinine values from labevents around patient's ICU stay\nWITH cr AS\n(\n    SELECT\n        ie.hadm_id\n        , ie.stay_id\n        , le.charttime\n        , AVG(le.valuenum) AS creat\n    FROM icustays ie\n    LEFT JOIN labevents le\n    ON ie.subject_id = le.subject_id\n    AND le.ITEMID = 50912\n    AND le.VALUENUM IS NOT NULL\n    AND le.VALUENUM <= 150\n    AND le.CHARTTIME BETWEEN DATETIME_SUB(ie.intime, interval '1 DAY' * ('7')) AND ie.outtime\n    GROUP BY ie.hadm_id, ie.stay_id, le.charttime\n)\n, cr48 AS\n(\n    -- add in the lowest value in the previous 48 hours\n    SELECT \n        cr.stay_id\n        , cr.charttime\n        , MIN(cr48.creat) AS creat_low_past_48hr\n    FROM cr\n    -- add in all creatinine values in the last 48 hours\n    LEFT JOIN cr cr48\n        ON cr.stay_id = cr48.stay_id\n        AND cr48.charttime <  cr.charttime\n        AND cr48.charttime >= DATETIME_SUB(cr.charttime, interval '1 HOUR' * ('48'))\n    GROUP BY cr.stay_id, cr.charttime\n)\n, cr7 AS\n(\n    -- add in the lowest value in the previous 7 days\n    SELECT\n        cr.stay_id\n        , cr.charttime\n        , MIN(cr7.creat) AS creat_low_past_7day\n    FROM cr\n    -- add in all creatinine values in the last 7 days\n    LEFT JOIN cr cr7\n      ON cr.stay_id = cr7.stay_id\n      AND cr7.charttime <  cr.charttime\n      AND cr7.charttime >= DATETIME_SUB(cr.charttime, interval '1 DAY' * ('7'))\n    GROUP BY cr.stay_id, cr.charttime\n)\nSELECT \n    cr.hadm_id\n    , cr.stay_id\n    , cr.charttime\n    , cr.creat\n    , cr48.creat_low_past_48hr\n    , cr7.creat_low_past_7day\nFROM cr\nLEFT JOIN cr48\n    ON cr.stay_id = cr48.stay_id\n    AND cr.charttime = cr48.charttime\nLEFT JOIN cr7\n    ON cr.stay_id = cr7.stay_id\n    AND cr.charttime = cr7.charttime\n;\n-- jing add tail\nalter table mimic4.organfailure_kdigo_creatinine\nowner to postgres;"
kdigo_uo <- "set search_path to mimic4;\ndrop materialized view if exists organfailure_kdigo_uo;\ncreate materialized view mimic4.organfailure_kdigo_uo\ntablespace pg_default\nas\n-- jing add head\nwith ur_stg as\n(\n  select io.stay_id, io.charttime\n  , sum(case when iosum.charttime >= DATETIME_SUB(io.charttime, interval '5' hour)\n      then iosum.urineoutput\n    else null end) as UrineOutput_6hr\n  -- 12 hours\n  , sum(case when iosum.charttime >= DATETIME_SUB(io.charttime, interval '11' hour)\n      then iosum.urineoutput\n    else null end) as UrineOutput_12hr\n  -- 24 hours\n  , sum(iosum.urineoutput) as UrineOutput_24hr\n  -- calculate the number of hours over which we've tabulated UO\n  , ROUND(CAST(\n      datetime_diff(io.charttime, \n        -- below MIN() gets the earliest time that was used in the summation \n        MIN(case when iosum.charttime >= DATETIME_SUB(io.charttime, interval '5' hour)\n          then iosum.charttime\n        else null end),\n        'SECOND') AS NUMERIC)/3600.0, 4)\n     AS uo_tm_6hr\n  -- repeat extraction for 12 hours and 24 hours\n  , ROUND(CAST(\n      datetime_diff(io.charttime,\n        MIN(case when iosum.charttime >= DATETIME_SUB(io.charttime, interval '11' hour)\n          then iosum.charttime\n        else null end),\n        'SECOND') AS NUMERIC)/3600.0, 4)\n   AS uo_tm_12hr\n  , ROUND(CAST(\n      datetime_diff(io.charttime, MIN(iosum.charttime), 'SECOND')\n   AS NUMERIC)/3600.0, 4) AS uo_tm_24hr\n  from measurement_urine_output io\n  -- this join gives all UO measurements over the 24 hours preceding this row\n  left join measurement_urine_output iosum\n    on  io.stay_id = iosum.stay_id\n    and iosum.charttime <= io.charttime\n    and iosum.charttime >= DATETIME_SUB(io.charttime, interval '23' hour)\n  group by io.stay_id, io.charttime\n)\nselect\n  ur.stay_id\n, ur.charttime\n, wd.weight\n, ur.urineoutput_6hr\n, ur.urineoutput_12hr\n, ur.urineoutput_24hr\n-- calculate rates - adding 1 hour as we assume data charted at 10:00 corresponds to previous hour\n, ROUND(CAST((ur.UrineOutput_6hr/wd.weight/(uo_tm_6hr+1))   AS NUMERIC), 4) AS uo_rt_6hr\n, ROUND(CAST((ur.UrineOutput_12hr/wd.weight/(uo_tm_12hr+1)) AS NUMERIC), 4) AS uo_rt_12hr\n, ROUND(CAST((ur.UrineOutput_24hr/wd.weight/(uo_tm_24hr+1)) AS NUMERIC), 4) AS uo_rt_24hr\n-- number of hours between current UO time and earliest charted UO within the X hour window\n, uo_tm_6hr\n, uo_tm_12hr\n, uo_tm_24hr\nfrom ur_stg ur\nleft join durations_weight_durations wd\n  on  ur.stay_id = wd.stay_id\n  and ur.charttime >= wd.starttime\n  and ur.charttime <  wd.endtime;\n-- jing add tail\nalter table mimic4.organfailure_kdigo_uo\nowner to postgres;"
kdigo_stages <- "set search_path to mimic4;\ndrop materialized view if exists organfailure_kdigo_stages;\ncreate materialized view mimic4.organfailure_kdigo_stages\ntablespace pg_default\nas\n-- jing add head\nwith cr_stg AS\n(\n  SELECT\n    cr.stay_id\n    , cr.charttime\n    , cr.creat_low_past_7day \n    , cr.creat_low_past_48hr\n    , cr.creat\n    , case\n        -- 3x baseline\n        when cr.creat >= (cr.creat_low_past_7day*3.0) then 3\n        -- *OR* cr >= 4.0 with associated increase\n        when cr.creat >= 4\n        -- For patients reaching Stage 3 by SCr >4.0 mg/dl\n        -- require that the patient first achieve ... acute increase >= 0.3 within 48 hr\n        -- *or* an increase of >= 1.5 times baseline\n        and (cr.creat_low_past_48hr <= 3.7 OR cr.creat >= (1.5*cr.creat_low_past_7day))\n            then 3 \n        -- TODO: initiation of rrt\n        when cr.creat >= (cr.creat_low_past_7day*2.0) then 2\n        when cr.creat >= (cr.creat_low_past_48hr+0.3) then 1\n        when cr.creat >= (cr.creat_low_past_7day*1.5) then 1\n    else 0 end as aki_stage_creat\n  FROM organfailure_kdigo_creatinine cr\n)\n-- stages for UO / creat\n, uo_stg as\n(\n  select\n      uo.stay_id\n    , uo.charttime\n    , uo.weight\n    , uo.uo_rt_6hr\n    , uo.uo_rt_12hr\n    , uo.uo_rt_24hr\n    -- AKI stages according to urine output\n    , CASE\n        WHEN uo.uo_rt_6hr IS NULL THEN NULL\n        -- require patient to be in ICU for at least 6 hours to stage UO\n        WHEN uo.charttime <= DATETIME_ADD(ie.intime, interval '1 HOUR' * ('6')) THEN 0\n        -- require the UO rate to be calculated over half the period\n        -- i.e. for uo rate over 24 hours, require documentation at least 12 hr apart\n        WHEN uo.uo_tm_24hr >= 11 AND uo.uo_rt_24hr < 0.3 THEN 3\n        WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr = 0 THEN 3\n        WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr < 0.5 THEN 2\n        WHEN uo.uo_tm_6hr >= 2 AND uo.uo_rt_6hr  < 0.5 THEN 1\n    ELSE 0 END AS aki_stage_uo\n  from organfailure_kdigo_uo uo\n  INNER JOIN icustays ie\n    ON uo.stay_id = ie.stay_id\n)\n-- get all charttimes documented\n, tm_stg AS\n(\n    SELECT\n      stay_id, charttime\n    FROM cr_stg\n    UNION DISTINCT\n    SELECT\n      stay_id, charttime\n    FROM uo_stg\n)\nselect\n    ie.subject_id\n  , ie.hadm_id\n  , ie.stay_id\n  , tm.charttime\n  , cr.creat_low_past_7day \n  , cr.creat_low_past_48hr\n  , cr.creat\n  , cr.aki_stage_creat\n  , uo.uo_rt_6hr\n  , uo.uo_rt_12hr\n  , uo.uo_rt_24hr\n  , uo.aki_stage_uo\n  -- Classify AKI using both creatinine/urine output criteria\n  , GREATEST(cr.aki_stage_creat, uo.aki_stage_uo) AS aki_stage\nFROM icustays ie\n-- get all possible charttimes as listed in tm_stg\nLEFT JOIN tm_stg tm\n  ON ie.stay_id = tm.stay_id\nLEFT JOIN cr_stg cr\n  ON ie.stay_id = cr.stay_id\n  AND tm.charttime = cr.charttime\nLEFT JOIN uo_stg uo\n  ON ie.stay_id = uo.stay_id\n  AND tm.charttime = uo.charttime\n;\n-- jing add tail\nalter table mimic4.organfailure_kdigo_stages\nowner to postgres;"
meld <- "set search_path to mimic4;\ndrop materialized view if exists organfailure_meld;\ncreate materialized view mimic4.organfailure_meld\ntablespace pg_default\nas\n-- jing add head\nWITH cohort AS\n(\nSELECT \n    ie.subject_id\n    , ie.hadm_id\n    , ie.stay_id\n    , ie.intime\n    , ie.outtime\n    , labs.creatinine_max\n    , labs.bilirubin_total_max\n    , labs.inr_max\n    , labs.sodium_min\n    , r.dialysis_present AS rrt\nFROM icustays ie\nLEFT JOIN firstday_first_day_lab labs\n  ON ie.stay_id = labs.stay_id\nLEFT JOIN firstday_first_day_rrt r\n  ON ie.stay_id = r.stay_id\n)\n, score as\n(\n  SELECT \n    subject_id\n    , hadm_id\n    , stay_id\n    , rrt\n    , creatinine_max\n    , bilirubin_total_max\n    , inr_max\n    , sodium_min\n    -- TODO: Corrected Sodium\n    , CASE\n        WHEN sodium_min is null\n          THEN 0.0\n        WHEN sodium_min > 137\n          THEN 0.0\n        WHEN sodium_min < 125\n          THEN 12.0 -- 137 - 125 = 12\n        else 137.0-sodium_min\n      end as sodium_score\n    -- if hemodialysis, value for Creatinine is automatically set to 4.0\n    , CASE\n        WHEN rrt = 1 or creatinine_max > 4.0\n          THEN (0.957 * ln(4))\n        -- if creatinine < 1, score is 1\n        WHEN creatinine_max < 1\n          THEN (0.957 * ln(1))\n        else 0.957 * coalesce(ln(creatinine_max),ln(1))\n      end as creatinine_score\n    , CASE\n        -- if value < 1, score is 1\n        WHEN bilirubin_total_max < 1\n          THEN 0.378 * ln(1)\n        else 0.378 * coalesce(ln(bilirubin_total_max),ln(1))\n      end as bilirubin_score\n    , CASE\n        WHEN inr_max < 1\n          THEN ( 1.120 * ln(1) + 0.643 )\n        else ( 1.120 * coalesce(ln(inr_max),ln(1)) + 0.643 )\n      end as inr_score\n\n  FROM cohort\n)\n, score2 as\n(\n  SELECT\n    subject_id\n    , hadm_id\n    , stay_id\n    , rrt\n    , creatinine_max\n    , bilirubin_total_max\n    , inr_max\n    , sodium_min\n    , creatinine_score\n    , sodium_score\n    , bilirubin_score\n    , inr_score\n    , CASE\n        WHEN (creatinine_score + bilirubin_score + inr_score) > 4\n          THEN 40.0\n        else\n          round(cast(creatinine_score + bilirubin_score + inr_score as numeric),1)*10\n        end as meld_initial\n  FROM score\n)\nSELECT\n  subject_id\n  , hadm_id\n  , stay_id\n  -- meld Score without sodium change\n  , meld_initial\n  , CASE\n      WHEN meld_initial > 11\n        THEN meld_initial + 1.32*sodium_score - 0.033*meld_initial*sodium_score\n      else\n        meld_initial\n      end as meld\n  -- original variables\n  , rrt\n  , creatinine_max\n  , bilirubin_total_max\n  , inr_max\n  , sodium_min\nFROM score2;\n-- jing add tail\nalter table mimic4.organfailure_meld\nowner to postgres;"

# score

apsiii <- "set search_path to mimic4;\ndrop materialized view if exists score_apsiii;\ncreate materialized view mimic4.score_apsiii\ntablespace pg_default\nas\n-- jing add head\nwith pa as\n(\n  select ie.stay_id, bg.charttime\n  , po2 as PaO2\n  , ROW_NUMBER() over (partition by ie.stay_id ORDER BY bg.po2 DESC) as rn\n  from measurement_bg bg\n  INNER JOIN icustays ie\n    ON bg.hadm_id = ie.hadm_id\n    AND bg.charttime >= ie.intime AND bg.charttime < ie.outtime\n  left join treatment_ventilation vd\n    on ie.stay_id = vd.stay_id\n    and bg.charttime >= vd.starttime\n    and bg.charttime <= vd.endtime\n    and vd.ventilation_status = 'InvasiveVent'\n  WHERE vd.stay_id is null -- patient is *not* ventilated\n  -- and fio2 < 50, or if no fio2, assume room air\n  AND coalesce(fio2, fio2_chartevents, 21) < 50\n  AND bg.po2 IS NOT NULL\n  AND bg.specimen_pred = 'ART.'\n)\n, aa as\n(\n  -- join blood gas to ventilation durations to determine if patient was vent\n  -- also join to cpap table for the same purpose\n  select ie.stay_id, bg.charttime\n  , bg.aado2\n  , ROW_NUMBER() over (partition by ie.stay_id ORDER BY bg.aado2 DESC) as rn\n  -- row number indicating the highest AaDO2\n  from measurement_bg bg\n  INNER JOIN icustays ie\n    ON bg.hadm_id = ie.hadm_id\n    AND bg.charttime >= ie.intime AND bg.charttime < ie.outtime\n  INNER JOIN treatment_ventilation vd\n    on ie.stay_id = vd.stay_id\n    and bg.charttime >= vd.starttime\n    and bg.charttime <= vd.endtime\n    and vd.ventilation_status = 'InvasiveVent'\n  WHERE vd.stay_id is not null -- patient is ventilated\n  AND coalesce(fio2, fio2_chartevents) >= 50\n  AND bg.aado2 IS NOT NULL\n  AND bg.specimen_pred = 'ART.'\n)\n-- because ph/pco2 rules are an interaction *within* a blood gas, we calculate them here\n-- the worse score is then taken for the final calculation\n, acidbase as\n(\n  select ie.stay_id\n  , ph, pco2 as paco2\n  , case\n      when ph is null or pco2 is null then null\n      when ph < 7.20 then\n        case\n          when pco2 < 50 then 12\n          else 4\n        end\n      when ph < 7.30 then\n        case\n          when pco2 < 30 then 9\n          when pco2 < 40 then 6\n          when pco2 < 50 then 3\n          else 2\n        end\n      when ph < 7.35 then\n        case\n          when pco2 < 30 then 9\n          when pco2 < 45 then 0\n          else 1\n        end\n      when ph < 7.45 then\n        case\n          when pco2 < 30 then 5\n          when pco2 < 45 then 0\n          else 1\n        end\n      when ph < 7.50 then\n        case\n          when pco2 < 30 then 5\n          when pco2 < 35 then 0\n          when pco2 < 45 then 2\n          else 12\n        end\n      when ph < 7.60 then\n        case\n          when pco2 < 40 then 3\n          else 12\n        end\n      else -- ph >= 7.60\n        case\n          when pco2 < 25 then 0\n          when pco2 < 40 then 3\n          else 12\n        end\n    end as acidbase_score\n  from measurement_bg bg\n  INNER JOIN icustays ie\n    ON bg.hadm_id = ie.hadm_id\n    AND bg.charttime >= ie.intime AND bg.charttime < ie.outtime\n  where ph is not null and pco2 is not null\n  AND bg.specimen_pred = 'ART.'\n)\n, acidbase_max as\n(\n  select stay_id, acidbase_score, ph, paco2\n    -- create integer which indexes maximum value of score with 1\n  , ROW_NUMBER() over (partition by stay_id ORDER BY acidbase_score DESC) as acidbase_rn\n  from acidbase\n)\n-- define acute renal failure (ARF) as:\n--  creatinine >=1.5 mg/dl\n--  and urine output <410 cc/day\n--  and no chronic dialysis\n, arf as\n(\n  select ie.stay_id\n    , case\n        when labs.creatinine_max >= 1.5\n        and  uo.urineoutput < 410\n        -- acute renal failure is only coded if the patient is not on chronic dialysis\n
    -- we use ICD-9 coding of ESRD as a proxy for chronic dialysis\n        and  icd.ckd = 0\n          then 1\n      else 0 end as arf\n  FROM icustays ie\n  left join firstday_first_day_urine_output uo\n    on ie.stay_id = uo.stay_id\n  left join firstday_first_day_lab labs\n    on ie.stay_id = labs.stay_id\n  left join\n  (\n    select hadm_id\n      , max(case\n          -- severe kidney failure requiring use of dialysis\n          when icd_version = 9 AND SUBSTR(icd_code, 1, 4) in ('5854','5855','5856') then 1\n          when icd_version = 10 AND SUBSTR(icd_code, 1, 4) in ('N184','N185','N186') then 1\n          -- we do not include 5859 as that is sometimes coded for acute-on-chronic ARF\n        else 0 end)\n      as ckd\n    from diagnoses_icd\n    group by hadm_id\n  ) icd\n    on ie.hadm_id = icd.hadm_id\n)\n-- first day mechanical ventilation\n, vent AS\n(\n    SELECT ie.stay_id\n    , MAX(\n        CASE WHEN v.stay_id IS NOT NULL THEN 1 ELSE 0 END\n    ) AS vent\n    FROM icustays ie\n    LEFT JOIN treatment_ventilation v\n        ON ie.stay_id = v.stay_id\n        AND (\n            v.starttime BETWEEN ie.intime AND DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        OR v.endtime BETWEEN ie.intime AND DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        OR v.starttime <= ie.intime AND v.endtime >= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        )\n        AND v.ventilation_status = 'InvasiveVent'\n    GROUP BY ie.stay_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.stay_id\n      , ie.intime\n      , ie.outtime\n\n      , vital.heart_rate_min\n      , vital.heart_rate_max\n      , vital.mbp_min\n      , vital.mbp_max\n      , vital.temperature_min\n      , vital.temperature_max\n      , vital.resp_rate_min\n      , vital.resp_rate_max\n\n      , pa.pao2\n      , aa.aado2\n\n      , ab.ph\n      , ab.paco2\n      , ab.acidbase_score\n\n      , labs.hematocrit_min\n      , labs.hematocrit_max\n      , labs.wbc_min\n      , labs.wbc_max\n      , labs.creatinine_min\n      , labs.creatinine_max\n      , labs.bun_min\n      , labs.bun_max\n      , labs.sodium_min\n      , labs.sodium_max\n      , labs.albumin_min\n      , labs.albumin_max\n      , labs.bilirubin_total_min AS bilirubin_min\n      , labs.bilirubin_total_max AS bilirubin_max\n\n      , case\n          when labs.glucose_max is null and vital.glucose_max is null\n            then null\n          when labs.glucose_max is null or vital.glucose_max > labs.glucose_max\n            then vital.glucose_max\n          when vital.glucose_max is null or labs.glucose_max > vital.glucose_max\n            then labs.glucose_max\n          else labs.glucose_max -- if equal, just pick labs\n        end as glucose_max\n\n      , case\n          when labs.glucose_min is null and vital.glucose_min is null\n            then null\n          when labs.glucose_min is null or vital.glucose_min < labs.glucose_min\n            then vital.glucose_min\n          when vital.glucose_min is null or labs.glucose_min < vital.glucose_min\n            then labs.glucose_min\n          else labs.glucose_min -- if equal, just pick labs\n        end as glucose_min\n\n      -- , labs.bicarbonate_min\n
    -- , labs.bicarbonate_max\n      , vent.vent\n      , uo.urineoutput\n      -- gcs and its components\n      , gcs.gcs_min AS mingcs\n      , gcs.gcs_motor, gcs.gcs_verbal,  gcs.gcs_eyes, gcs.gcs_unable\n      -- acute renal failure\n      , arf.arf as arf\n\nFROM icustays ie\ninner join admissions adm\n  on ie.hadm_id = adm.hadm_id\ninner join patients pat\n  on ie.subject_id = pat.subject_id\n\n-- join to above views - the row number filters to 1 row per stay_id\nleft join pa\n  on  ie.stay_id = pa.stay_id\n  and pa.rn = 1\nleft join aa\n  on  ie.stay_id = aa.stay_id\n  and aa.rn = 1\nleft join acidbase_max ab\n  on  ie.stay_id = ab.stay_id\n  and ab.acidbase_rn = 1\nleft join arf\n  on ie.stay_id = arf.stay_id\n\n-- join to custom tables to get more data....\nleft join vent\n  on ie.stay_id = vent.stay_id\nleft join firstday_first_day_gcs gcs\n  on ie.stay_id = gcs.stay_id\nleft join firstday_first_day_vitalsign vital\n  on ie.stay_id = vital.stay_id\nleft join firstday_first_day_urine_output uo\n  on ie.stay_id = uo.stay_id\nleft join firstday_first_day_lab labs\n  on ie.stay_id = labs.stay_id\n)\n-- First, we calculate the score for the minimum values\n, score_min as\n(\n  select cohort.subject_id, cohort.hadm_id, cohort.stay_id\n  , case\n      when heart_rate_min is null then null\n      when heart_rate_min <   40 then 8\n      when heart_rate_min <   50 then 5\n      when heart_rate_min <  100 then 0\n      when heart_rate_min <  110 then 1\n      when heart_rate_min <  120 then 5\n      when heart_rate_min <  140 then 7\n      when heart_rate_min <  155 then 13\n      when heart_rate_min >= 155 then 17\n    end as hr_score\n\n  , case\n      when mbp_min is null then null\n      when mbp_min <   40 then 23\n      when mbp_min <   60 then 15\n      when mbp_min <   70 then 7\n      when mbp_min <   80 then 6\n      when mbp_min <  100 then 0\n      when mbp_min <  120 then 4\n      when mbp_min <  130 then 7\n      when mbp_min <  140 then 9\n      when mbp_min >= 140 then 10\n    end as mbp_score\n\n  -- TODO: add 1 degree to axillary measurements\n  , case\n      when temperature_min is null then null\n      when temperature_min <  33.0 then 20\n      when temperature_min <  33.5 then 16\n      when temperature_min <  34.0 then 13\n      when temperature_min <  35.0 then 8\n      when temperature_min <  36.0 then 2\n      when temperature_min <  40.0 then 0\n      when temperature_min >= 40.0 then 4\n    end as temp_score\n\n  , case\n      when resp_rate_min is null then null\n
    -- special case for ventilated patients\n      when vent = 1 and resp_rate_min < 14 then 0\n      when resp_rate_min <   6 then 17\n      when resp_rate_min <  12 then 8\n      when resp_rate_min <  14 then 7\n      when resp_rate_min <  25 then 0\n      when resp_rate_min <  35 then 6\n      when resp_rate_min <  40 then 9\n      when resp_rate_min <  50 then 11\n      when resp_rate_min >= 50 then 18\n    end as resp_rate_score\n\n  , case\n      when hematocrit_min is null then null\n      when hematocrit_min <   41.0 then 3\n      when hematocrit_min <   50.0 then 0\n      when hematocrit_min >=  50.0 then 3\n    end as hematocrit_score\n\n  , case\n      when wbc_min is null then null\n      when wbc_min <   1.0 then 19\n      when wbc_min <   3.0 then 5\n      when wbc_min <  20.0 then 0\n      when wbc_min <  25.0 then 1\n      when wbc_min >= 25.0 then 5\n    end as wbc_score\n\n  , case\n      when creatinine_min is null then null\n      when arf = 1 and creatinine_min <  1.5 then 0\n      when arf = 1 and creatinine_min >= 1.5 then 10\n      when creatinine_min <   0.5 then 3\n      when creatinine_min <   1.5 then 0\n      when creatinine_min <  1.95 then 4\n      when creatinine_min >= 1.95 then 7\n    end as creatinine_score\n\n  , case\n      when bun_min is null then null\n      when bun_min <  17.0 then 0\n      when bun_min <  20.0 then 2\n      when bun_min <  40.0 then 7\n      when bun_min <  80.0 then 11\n      when bun_min >= 80.0 then 12\n    end as bun_score\n\n  , case\n      when sodium_min is null then null\n      when sodium_min <  120 then 3\n      when sodium_min <  135 then 2\n      when sodium_min <  155 then 0\n      when sodium_min >= 155 then 4\n    end as sodium_score\n\n  , case\n      when albumin_min is null then null\n      when albumin_min <  2.0 then 11\n      when albumin_min <  2.5 then 6\n      when albumin_min <  4.5 then 0\n      when albumin_min >= 4.5 then 4\n    end as albumin_score\n\n  , case\n      when bilirubin_min is null then null\n      when bilirubin_min <  2.0 then 0\n      when bilirubin_min <  3.0 then 5\n      when bilirubin_min <  5.0 then 6\n      when bilirubin_min <  8.0 then 8\n      when bilirubin_min >= 8.0 then 16\n    end as bilirubin_score\n\n  , case\n      when glucose_min is null then null\n      when glucose_min <   40 then 8\n      when glucose_min <   60 then 9\n      when glucose_min <  200 then 0\n      when glucose_min <  350 then 3\n      when glucose_min >= 350 then 5\n    end as glucose_score\n\nfrom cohort\n)\n, score_max as\n(\n  select cohort.subject_id, cohort.hadm_id, cohort.stay_id\n    , case\n        when heart_rate_max is null then null\n        when heart_rate_max <   40 then 8\n        when heart_rate_max <   50 then 5\n        when heart_rate_max <  100 then 0\n        when heart_rate_max <  110 then 1\n        when heart_rate_max <  120 then 5\n        when heart_rate_max <  140 then 7\n        when heart_rate_max <  155 then 13\n        when heart_rate_max >= 155 then 17\n      end as hr_score\n\n    , case\n        when mbp_max is null then null\n        when mbp_max <   40 then 23\n        when mbp_max <   60 then 15\n        when mbp_max <   70 then 7\n        when mbp_max <   80 then 6\n        when mbp_max <  100 then 0\n        when mbp_max <  120 then 4\n        when mbp_max <  130 then 7\n        when mbp_max <  140 then 9\n        when mbp_max >= 140 then 10\n      end as mbp_score\n\n
    -- TODO: add 1 degree to axillary measurements\n    , case\n        when temperature_max is null then null\n        when temperature_max <  33.0 then 20\n        when temperature_max <  33.5 then 16\n        when temperature_max <  34.0 then 13\n        when temperature_max <  35.0 then 8\n        when temperature_max <  36.0 then 2\n        when temperature_max <  40.0 then 0\n        when temperature_max >= 40.0 then 4\n      end as temp_score\n\n    , case\n        when resp_rate_max is null then null\n        -- special case for ventilated patients\n        when vent = 1 and resp_rate_max < 14 then 0\n        when resp_rate_max <   6 then 17\n        when resp_rate_max <  12 then 8\n        when resp_rate_max <  14 then 7\n        when resp_rate_max <  25 then 0\n        when resp_rate_max <  35 then 6\n        when resp_rate_max <  40 then 9\n        when resp_rate_max <  50 then 11\n        when resp_rate_max >= 50 then 18\n      end as resp_rate_score\n\n    , case\n        when hematocrit_max is null then null\n        when hematocrit_max <   41.0 then 3\n        when hematocrit_max <   50.0 then 0\n        when hematocrit_max >=  50.0 then 3\n      end as hematocrit_score\n\n    , case\n        when wbc_max is null then null\n        when wbc_max <   1.0 then 19\n        when wbc_max <   3.0 then 5\n        when wbc_max <  20.0 then 0\n        when wbc_max <  25.0 then 1\n        when wbc_max >= 25.0 then 5\n      end as wbc_score\n\n    , case\n        when creatinine_max is null then null\n        when arf = 1 and creatinine_max <  1.5 then 0\n        when arf = 1 and creatinine_max >= 1.5 then 10\n        when creatinine_max <   0.5 then 3\n        when creatinine_max <   1.5 then 0\n        when creatinine_max <  1.95 then 4\n        when creatinine_max >= 1.95 then 7\n      end as creatinine_score\n\n    , case\n        when bun_max is null then null\n        when bun_max <  17.0 then 0\n        when bun_max <  20.0 then 2\n        when bun_max <  40.0 then 7\n        when bun_max <  80.0 then 11\n        when bun_max >= 80.0 then 12\n      end as bun_score\n\n    , case\n        when sodium_max is null then null\n        when sodium_max <  120 then 3\n        when sodium_max <  135 then 2\n        when sodium_max <  155 then 0\n        when sodium_max >= 155 then 4\n      end as sodium_score\n\n    , case\n        when albumin_max is null then null\n        when albumin_max <  2.0 then 11\n        when albumin_max <  2.5 then 6\n        when albumin_max <  4.5 then 0\n        when albumin_max >= 4.5 then 4\n      end as albumin_score\n\n    , case\n        when bilirubin_max is null then null\n        when bilirubin_max <  2.0 then 0\n        when bilirubin_max <  3.0 then 5\n        when bilirubin_max <  5.0 then 6\n        when bilirubin_max <  8.0 then 8\n        when bilirubin_max >= 8.0 then 16\n      end as bilirubin_score\n\n    , case\n        when glucose_max is null then null\n        when glucose_max <   40 then 8\n        when glucose_max <   60 then 9\n        when glucose_max <  200 then 0\n        when glucose_max <  350 then 3\n        when glucose_max >= 350 then 5\n      end as glucose_score\n\nfrom cohort\n)\n-- Combine together the scores for min/max, using the following rules:\n
    --  1) select the value furthest from a predefined normal value\n--  2) if both equidistant, choose the one which gives a worse score\n--  3) calculate score for acid-base abnormalities as it requires interactions\n-- sometimes the code is a bit redundant, i.e. we know the max would always be furthest from 0\n, scorecomp as\n(\n  select co.*\n  -- The rules for APS III require the definition of a \\\"worst\\\" value\n  -- This value is defined as whatever value is furthest from a predefined normal\n  -- e.g., for heart rate, worst is defined as furthest from 75\n  , case\n      when heart_rate_max is null then null\n      when abs(heart_rate_max-75) > abs(heart_rate_min-75)\n        then smax.hr_score\n      when abs(heart_rate_max-75) < abs(heart_rate_min-75)\n        then smin.hr_score\n      when abs(heart_rate_max-75) = abs(heart_rate_min-75)\n      and  smax.hr_score >= smin.hr_score\n        then smax.hr_score\n      when abs(heart_rate_max-75) = abs(heart_rate_min-75)\n      and  smax.hr_score < smin.hr_score\n        then smin.hr_score\n    end as hr_score\n\n  , case\n      when mbp_max is null then null\n      when abs(mbp_max-90) > abs(mbp_min-90)\n        then smax.mbp_score\n      when abs(mbp_max-90) < abs(mbp_min-90)\n        then smin.mbp_score\n      -- values are equidistant - pick the larger score\n      when abs(mbp_max-90) = abs(mbp_min-90)\n      and  smax.mbp_score >= smin.mbp_score\n        then smax.mbp_score\n      when abs(mbp_max-90) = abs(mbp_min-90)\n      and  smax.mbp_score < smin.mbp_score\n        then smin.mbp_score\n    end as mbp_score\n\n  , case\n      when temperature_max is null then null\n      when abs(temperature_max-38) > abs(temperature_min-38)\n        then smax.temp_score\n      when abs(temperature_max-38) < abs(temperature_min-38)\n        then smin.temp_score\n      -- values are equidistant - pick the larger score\n      when abs(temperature_max-38) = abs(temperature_min-38)\n      and  smax.temp_score >= smin.temp_score\n        then smax.temp_score\n      when abs(temperature_max-38) = abs(temperature_min-38)\n      and  smax.temp_score < smin.temp_score\n        then smin.temp_score\n    end as temp_score\n\n  , case\n      when resp_rate_max is null then null\n      when abs(resp_rate_max-19) > abs(resp_rate_min-19)\n        then smax.resp_rate_score\n      when abs(resp_rate_max-19) < abs(resp_rate_min-19)\n        then smin.resp_rate_score\n      -- values are equidistant - pick the larger score\n      when abs(resp_rate_max-19) = abs(resp_rate_max-19)\n      and  smax.resp_rate_score >= smin.resp_rate_score\n        then smax.resp_rate_score\n      when abs(resp_rate_max-19) = abs(resp_rate_max-19)\n      and  smax.resp_rate_score < smin.resp_rate_score\n        then smin.resp_rate_score\n    end as resp_rate_score\n\n  , case\n      when hematocrit_max is null then null\n      when abs(hematocrit_max-45.5) > abs(hematocrit_min-45.5)\n        then smax.hematocrit_score\n      when abs(hematocrit_max-45.5) < abs(hematocrit_min-45.5)\n        then smin.hematocrit_score\n      -- values are equidistant - pick the larger score\n      when abs(hematocrit_max-45.5) = abs(hematocrit_max-45.5)\n      and  smax.hematocrit_score >= smin.hematocrit_score\n        then smax.hematocrit_score\n      when abs(hematocrit_max-45.5) = abs(hematocrit_max-45.5)\n      and  smax.hematocrit_score < smin.hematocrit_score\n        then smin.hematocrit_score\n    end as hematocrit_score\n\n  , case\n      when wbc_max is null then null\n      when abs(wbc_max-11.5) > abs(wbc_min-11.5)\n        then smax.wbc_score\n      when abs(wbc_max-11.5) < abs(wbc_min-11.5)\n        then smin.wbc_score\n
    -- values are equidistant - pick the larger score\n      when abs(wbc_max-11.5) = abs(wbc_max-11.5)\n      and  smax.wbc_score >= smin.wbc_score\n        then smax.wbc_score\n      when abs(wbc_max-11.5) = abs(wbc_max-11.5)\n      and  smax.wbc_score < smin.wbc_score\n        then smin.wbc_score\n    end as wbc_score\n\n\n  -- For some labs, \\\"furthest from normal\\\" doesn't make sense\n  -- e.g. creatinine w/ ARF, the minimum could be 0.3, and the max 1.6\n  -- while the minimum of 0.3 is \\\"further from 1\\\", seems like the max should be scored\n\n  , case\n      when creatinine_max is null then null\n      -- if they have arf then use the max to score\n      when arf = 1 then smax.creatinine_score\n      -- otherwise furthest from 1\n      when abs(creatinine_max-1) > abs(creatinine_min-1)\n        then smax.creatinine_score\n      when abs(creatinine_max-1) < abs(creatinine_min-1)\n        then smin.creatinine_score\n      -- values are equidistant\n      when smax.creatinine_score >= smin.creatinine_score\n        then smax.creatinine_score\n      when smax.creatinine_score < smin.creatinine_score\n        then smin.creatinine_score\n    end as creatinine_score\n\n  -- the rule for BUN is the furthest from 0.. equivalent to the max value\n  , case\n      when bun_max is null then null\n      else smax.bun_score\n    end as bun_score\n\n  , case\n      when sodium_max is null then null\n      when abs(sodium_max-145.5) > abs(sodium_min-145.5)\n        then smax.sodium_score\n      when abs(sodium_max-145.5) < abs(sodium_min-145.5)\n        then smin.sodium_score\n      -- values are equidistant - pick the larger score\n      when abs(sodium_max-145.5) = abs(sodium_max-145.5)\n      and  smax.sodium_score >= smin.sodium_score\n        then smax.sodium_score\n      when abs(sodium_max-145.5) = abs(sodium_max-145.5)\n      and  smax.sodium_score < smin.sodium_score\n        then smin.sodium_score\n    end as sodium_score\n\n  , case\n      when albumin_max is null then null\n      when abs(albumin_max-3.5) > abs(albumin_min-3.5)\n        then smax.albumin_score\n      when abs(albumin_max-3.5) < abs(albumin_min-3.5)\n        then smin.albumin_score\n      -- values are equidistant - pick the larger score\n      when abs(albumin_max-3.5) = abs(albumin_max-3.5)\n      and  smax.albumin_score >= smin.albumin_score\n        then smax.albumin_score\n      when abs(albumin_max-3.5) = abs(albumin_max-3.5)\n      and  smax.albumin_score < smin.albumin_score\n        then smin.albumin_score\n    end as albumin_score\n\n  , case\n      when bilirubin_max is null then null\n      else smax.bilirubin_score\n    end as bilirubin_score\n\n  , case\n      when glucose_max is null then null\n      when abs(glucose_max-130) > abs(glucose_min-130)\n        then smax.glucose_score\n      when abs(glucose_max-130) < abs(glucose_min-130)\n        then smin.glucose_score\n      -- values are equidistant - pick the larger score\n      when abs(glucose_max-130) = abs(glucose_max-130)\n      and  smax.glucose_score >= smin.glucose_score\n        then smax.glucose_score\n      when abs(glucose_max-130) = abs(glucose_max-130)\n      and  smax.glucose_score < smin.glucose_score\n        then smin.glucose_score\n    end as glucose_score\n\n\n
    -- Below are interactions/special cases where only 1 value is important\n  , case\n      when urineoutput is null then null\n      when urineoutput <   400 then 15\n      when urineoutput <   600 then 8\n      when urineoutput <   900 then 7\n      when urineoutput <  1500 then 5\n      when urineoutput <  2000 then 4\n      when urineoutput <  4000 then 0\n      when urineoutput >= 4000 then 1\n  end as uo_score\n\n  , case\n      when gcs_unable = 1\n        -- here they are intubated, so their verbal score is inappropriate\n        -- normally you are supposed to use \\\"clinical judgement\\\"\n        -- we don't have that, so we just assume normal (as was done in the original study)\n        then 0\n      when gcs_eyes = 1\n        then case\n          when gcs_verbal = 1 and gcs_motor in (1,2)\n            then 48\n          when gcs_verbal = 1 and gcs_motor in (3,4)\n            then 33\n          when gcs_verbal = 1 and gcs_motor in (5,6)\n            then 16\n          when gcs_verbal in (2,3) and gcs_motor in (1,2)\n            then 29\n          when gcs_verbal in (2,3) and gcs_motor in (3,4)\n            then 24\n          when gcs_verbal in (2,3) and gcs_motor >= 5\n            -- highly unlikely clinical combination\n            then null\n          when gcs_verbal >= 4\n            then null\n          end\n      when gcs_eyes > 1\n        then case\n          when gcs_verbal = 1 and gcs_motor in (1,2)\n            then 29\n          when gcs_verbal = 1 and gcs_motor in (3,4)\n            then 24\n          when gcs_verbal = 1 and gcs_motor in (5,6)\n            then 15\n          when gcs_verbal in (2,3) and gcs_motor in (1,2)\n            then 29\n          when gcs_verbal in (2,3) and gcs_motor in (3,4)\n            then 24\n          when gcs_verbal in (2,3) and gcs_motor = 5\n            then 13\n          when gcs_verbal in (2,3) and gcs_motor = 6\n            then 10\n          when gcs_verbal = 4 and gcs_motor in (1,2,3,4)\n            then 13\n          when gcs_verbal = 4 and gcs_motor = 5\n            then 8\n          when gcs_verbal = 4 and gcs_motor = 6\n            then 3\n          when gcs_verbal = 5 and gcs_motor in (1,2,3,4,5)\n            then 3\n          when gcs_verbal = 5 and gcs_motor = 6\n            then 0\n          end\n      else null\n    end as gcs_score\n\n  , case\n      when pao2 is null and aado2 is null\n        then null\n      when pao2 is not null then\n        case\n          when pao2 < 50 then 15\n          when pao2 < 70 then 5\n          when pao2 < 80 then 2\n        else 0 end\n      when aado2 is not null then\n        case\n          when aado2 <  100 then 0\n          when aado2 <  250 then 7\n          when aado2 <  350 then 9\n          when aado2 <  500 then 11\n          when aado2 >= 500 then 14\n        else 0 end\n      end as pao2_aado2_score\n\nfrom cohort co\nleft join score_min smin\n  on co.stay_id = smin.stay_id\nleft join score_max smax\n  on co.stay_id = smax.stay_id\n)\n-- tabulate the APS III using the scores from the worst values\n, score as\n(\n  select s.*\n
    -- coalesce statements impute normal score of zero if data element is missing\n  , coalesce(hr_score,0)\n  + coalesce(mbp_score,0)\n  + coalesce(temp_score,0)\n  + coalesce(resp_rate_score,0)\n  + coalesce(pao2_aado2_score,0)\n  + coalesce(hematocrit_score,0)\n  + coalesce(wbc_score,0)\n  + coalesce(creatinine_score,0)\n  + coalesce(uo_score,0)\n  + coalesce(bun_score,0)\n  + coalesce(sodium_score,0)\n  + coalesce(albumin_score,0)\n  + coalesce(bilirubin_score,0)\n  + coalesce(glucose_score,0)\n  + coalesce(acidbase_score,0)\n  + coalesce(gcs_score,0)\n    as apsiii\n  from scorecomp s\n)\nselect ie.subject_id, ie.hadm_id, ie.stay_id\n, apsiii\n-- Calculate probability of hospital mortality using equation from Johnson 2014.\n, 1 / (1 + exp(- (-4.4360 + 0.04726*(apsiii) ))) as apsiii_prob\n, hr_score\n, mbp_score\n, temp_score\n, resp_rate_score\n, pao2_aado2_score\n, hematocrit_score\n, wbc_score\n, creatinine_score\n, uo_score\n, bun_score\n, sodium_score\n, albumin_score\n, bilirubin_score\n, glucose_score\n, acidbase_score\n, gcs_score\nFROM icustays ie\nleft join score s\n  on ie.stay_id = s.stay_id\n;\n-- jing add tail\nalter table mimic4.score_apsiii\nowner to postgres;"
lods <- "set search_path to mimic4;\ndrop materialized view if exists score_lods;\ncreate materialized view mimic4.score_lods\ntablespace pg_default\nas\n-- jing add head\nwith cpap as\n(\n  select ie.stay_id\n    , min(DATETIME_SUB(charttime, interval '1 HOUR' * ('1'))) as starttime\n    , max(DATETIME_ADD(charttime, interval '1 HOUR' * ('4'))) as endtime\n    , max(CASE\n          WHEN lower(ce.value) LIKE '%cpap%' THEN 1\n          WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1\n        else 0 end) as cpap\n  FROM icustays ie\n  inner join chartevents ce\n    on ie.stay_id = ce.stay_id\n    and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  where itemid = 226732\n  and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%')\n  group by ie.stay_id\n)\n, pafi1 as\n(\n  -- join blood gas to ventilation durations to determine if patient was vent\n  -- also join to cpap table for the same purpose\n  select ie.stay_id, bg.charttime\n  , pao2fio2ratio\n  , case when vd.stay_id is not null then 1 else 0 end as vent\n  , case when cp.stay_id is not null then 1 else 0 end as cpap\n  from measurement_bg bg\n  INNER JOIN icustays ie\n    ON bg.hadm_id = ie.hadm_id\n    AND bg.charttime >= ie.intime AND bg.charttime < ie.outtime\n  left join treatment_ventilation vd\n    on ie.stay_id = vd.stay_id\n    and bg.charttime >= vd.starttime\n    and bg.charttime <= vd.endtime\n    and vd.ventilation_status = 'InvasiveVent'\n  left join cpap cp\n    on ie.stay_id = cp.stay_id\n    and bg.charttime >= cp.starttime\n    and bg.charttime <= cp.endtime\n)\n, pafi2 as\n(\n  -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients*\n  select stay_id\n  , min(pao2fio2ratio) as pao2fio2_vent_min\n  from pafi1\n  where vent = 1 or cpap = 1\n  group by stay_id\n)\n, cohort as\n(\nselect  ie.subject_id\n      , ie.hadm_id\n      , ie.stay_id\n      , ie.intime\n      , ie.outtime\n\n      , gcs.gcs_min\n      , vital.heart_rate_max\n      , vital.heart_rate_min\n      , vital.sbp_max\n      , vital.sbp_min\n\n      -- this value is non-null iff the patient is on vent/cpap\n      , pf.pao2fio2_vent_min\n\n      , labs.bun_max\n      , labs.bun_min\n      , labs.wbc_max\n      , labs.wbc_min\n      , labs.bilirubin_total_max AS bilirubin_max\n      , labs.creatinine_max\n      , labs.pt_min\n      , labs.pt_max\n      , labs.platelets_min AS platelet_min\n\n      , uo.urineoutput\n\nFROM icustays ie\ninner join admissions adm\n  on ie.hadm_id = adm.hadm_id\ninner join patients pat\n  on ie.subject_id = pat.subject_id\n\n-- join to above view to get pao2/fio2 ratio\nleft join pafi2 pf\n  on ie.stay_id = pf.stay_id\n\n
    -- join to custom tables to get more data....\nleft join firstday_first_day_gcs gcs\n  on ie.stay_id = gcs.stay_id\nleft join firstday_first_day_vitalsign vital\n  on ie.stay_id = vital.stay_id\nleft join firstday_first_day_urine_output uo\n  on ie.stay_id = uo.stay_id\nleft join firstday_first_day_lab labs\n  on ie.stay_id = labs.stay_id\n)\n, scorecomp as\n(\nselect\n  cohort.*\n  -- Below code calculates the component scores needed for SAPS\n\n  -- neurologic\n  , case\n    when gcs_min is null then null\n      when gcs_min <  3 then null -- erroneous value/on trach\n      when gcs_min <=  5 then 5\n      when gcs_min <=  8 then 3\n      when gcs_min <= 13 then 1\n    else 0\n  end as neurologic\n\n  -- cardiovascular\n  , case\n      when heart_rate_max is null\n      and sbp_min is null then null\n      when heart_rate_min < 30 then 5\n      when sbp_min < 40 then 5\n      when sbp_min <  70 then 3\n      when sbp_max >= 270 then 3\n      when heart_rate_max >= 140 then 1\n      when sbp_max >= 240 then 1\n      when sbp_min < 90 then 1\n    else 0\n  end as cardiovascular\n\n  -- renal\n  , case\n      when bun_max is null\n        or urineoutput is null\n        or creatinine_max is null\n        then null\n      when urineoutput <   500.0 then 5\n      when bun_max >= 56.0 then 5\n      when creatinine_max >= 1.60 then 3\n      when urineoutput <   750.0 then 3\n      when bun_max >= 28.0 then 3\n      when urineoutput >= 10000.0 then 3\n      when creatinine_max >= 1.20 then 1\n      when bun_max >= 17.0 then 1\n      when bun_max >= 7.50 then 1\n    else 0\n  end as renal\n\n  -- pulmonary\n  , case\n      when pao2fio2_vent_min is null then 0\n      when pao2fio2_vent_min >= 150 then 1\n      when pao2fio2_vent_min < 150 then 3\n    else null\n  end as pulmonary\n\n  -- hematologic\n  , case\n      when wbc_max is null\n        and platelet_min is null\n          then null\n      when wbc_min <   1.0 then 3\n      when wbc_min <   2.5 then 1\n      when platelet_min < 50.0 then 1\n      when wbc_max >= 50.0 then 1\n    else 0\n  end as hematologic\n\n  -- hepatic\n  -- We have defined the \\\"standard\\\" PT as 12 seconds.\n  -- This is an assumption and subsequent analyses may be affected by this assumption.\n  , case\n      when pt_max is null\n        and bilirubin_max is null\n          then null\n      when bilirubin_max >= 2.0 then 1\n      when pt_max > (12+3) then 1\n      when pt_min < (12*0.25) then 1\n    else 0\n  end as hepatic\n\nfrom cohort\n)\nselect ie.subject_id, ie.hadm_id, ie.stay_id\n-- coalesce statements impute normal score of zero if data element is missing\n, coalesce(neurologic,0)\n+ coalesce(cardiovascular,0)\n+ coalesce(renal,0)\n+ coalesce(pulmonary,0)\n+ coalesce(hematologic,0)\n+ coalesce(hepatic,0)\n  as lods\n, neurologic\n, cardiovascular\n, renal\n, pulmonary\n, hematologic\n, hepatic\nFROM icustays ie\nleft join scorecomp s\n  on ie.stay_id = s.stay_id\n;\n-- jing add tail\nalter table mimic4.score_lods\nowner to postgres;"

oasis <- "set search_path to mimic4;\ndrop materialized view if exists score_oasis;\ncreate materialized view mimic4.score_oasis\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Oxford Acute Severity of Illness Score (oasis)\n-- This query extracts the Oxford acute severity of illness score.\n-- This score is a measure of severity of illness for patients in the ICU.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for oasis:\n--    Johnson, Alistair EW, Andrew A. Kramer, and Gari D. Clifford.\n--    \\\"A new severity of illness scale using a subset of acute physiology and chronic health evaluation data elements shows comparable predictive accuracy*.\\\"\n--    Critical care medicine 41, no. 7 (2013): 1711-1718.\n\n-- Variables used in oasis:\n--  Heart rate, gcs, MAP, Temperature, Respiratory rate, ventilation status (sourced FROM chartevents)\n--  Urine output (sourced from OUTPUTEVENTS)\n--  Elective surgery (sourced FROM admissions and SERVICES)\n--  Pre-ICU in-hospital length of stay (sourced FROM admissions and ICUSTAYS)\n--  age (sourced FROM patients)\n\n-- Regarding missing values:\n--  The ventilation flag is always 0/1. It cannot be missing, since VENT=0 if no data is found for vent settings.\n\n-- Note:\n--  The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate stay_ids.\n--  For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n\nwith surgflag as\n(\n  select ie.stay_id\n    , max(case\n        when lower(curr_service) like '%surg%' then 1\n        when curr_service = 'ORTHO' then 1\n    else 0 end) as surgical\n  FROM icustays ie\n  left join services se\n    on ie.hadm_id = se.hadm_id\n    and se.transfertime < DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  group by ie.stay_id\n)\n-- first day ventilation\n, vent AS\n(\n    SELECT ie.stay_id\n    , MAX(\n        CASE WHEN v.stay_id IS NOT NULL THEN 1 ELSE 0 END\n    ) AS vent\n    FROM icustays ie\n    LEFT JOIN treatment_ventilation v\n        ON ie.stay_id = v.stay_id\n        AND (\n            v.starttime BETWEEN ie.intime AND DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        OR v.endtime BETWEEN ie.intime AND DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        OR v.starttime <= ie.intime AND v.endtime >= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n        )\n        AND v.ventilation_status = 'InvasiveVent'\n    GROUP BY ie.stay_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.stay_id\n      , ie.intime\n      , ie.outtime\n      , adm.deathtime\n      , datetime_diff(ie.intime, adm.admittime, 'MINUTE') as preiculos\n      , ag.age\n      , gcs.gcs_min\n      , vital.heart_rate_max\n      , vital.heart_rate_min\n      , vital.mbp_max\n      , vital.mbp_min\n      , vital.resp_rate_max\n      , vital.resp_rate_min\n      , vital.temperature_max\n      , vital.temperature_min\n      , vent.vent as mechvent\n      , uo.urineoutput\n\n      , case\n          when adm.ADMISSION_TYPE = 'ELECTIVE' and sf.surgical = 1\n            then 1\n          when adm.ADMISSION_TYPE is null or sf.surgical is null\n            then null\n          else 0\n        end as electivesurgery\n\n      -- mortality flags\n      , case\n          when adm.deathtime between ie.intime and ie.outtime\n            then 1\n          when adm.deathtime <= ie.intime
    -- sometimes there are typographical errors in the death date\n            then 1\n          when adm.dischtime <= ie.outtime and adm.discharge_location = 'DEAD/EXPIRED'\n            then 1\n          else 0 end\n        as icustay_expire_flag\n      , adm.hospital_expire_flag\nFROM icustays ie\ninner join admissions adm\n  on ie.hadm_id = adm.hadm_id\ninner join patients pat\n  on ie.subject_id = pat.subject_id\nLEFT JOIN demographics_age ag\n  ON ie.hadm_id = ag.hadm_id\nleft join surgflag sf\n  on ie.stay_id = sf.stay_id\n-- join to custom tables to get more data....\nleft join firstday_first_day_gcs gcs\n  on ie.stay_id = gcs.stay_id\nleft join firstday_first_day_vitalsign vital\n  on ie.stay_id = vital.stay_id\nleft join firstday_first_day_urine_output uo\n  on ie.stay_id = uo.stay_id\nleft join vent\n  on ie.stay_id = vent.stay_id\n)\n, scorecomp as\n(\nselect co.subject_id, co.hadm_id, co.stay_id\n, co.icustay_expire_flag\n, co.hospital_expire_flag\n\n-- Below code calculates the component scores needed for oasis\n, case when preiculos is null then null\n     when preiculos < 10.2 then 5\n     when preiculos < 297 then 3\n     when preiculos < 1440 then 0\n     when preiculos < 18708 then 1\n     else 2 end as preiculos_score\n,  case when age is null then null\n      when age < 24 then 0\n      when age <= 53 then 3\n      when age <= 77 then 6\n      when age <= 89 then 9\n      when age >= 90 then 7\n      else 0 end as age_score\n,  case when gcs_min is null then null\n      when gcs_min <= 7 then 10\n      when gcs_min < 14 then 4\n      when gcs_min = 14 then 3\n      else 0 end as gcs_score\n,  case when heart_rate_max is null then null\n      when heart_rate_max > 125 then 6\n      when heart_rate_min < 33 then 4\n      when heart_rate_max >= 107 and heart_rate_max <= 125 then 3\n      when heart_rate_max >= 89 and heart_rate_max <= 106 then 1\n      else 0 end as heart_rate_score\n,  case when mbp_min is null then null\n      when mbp_min < 20.65 then 4\n      when mbp_min < 51 then 3\n      when mbp_max > 143.44 then 3\n      when mbp_min >= 51 and mbp_min < 61.33 then 2\n      else 0 end as mbp_score\n,  case when resp_rate_min is null then null\n      when resp_rate_min <   6 then 10\n      when resp_rate_max >  44 then  9\n      when resp_rate_max >  30 then  6\n      when resp_rate_max >  22 then  1\n      when resp_rate_min <  13 then 1 else 0\n      end as resp_rate_score\n,  case when temperature_max is null then null\n      when temperature_max > 39.88 then 6\n      when temperature_min >= 33.22 and temperature_min <= 35.93 then 4\n      when temperature_max >= 33.22 and temperature_max <= 35.93 then 4\n      when temperature_min < 33.22 then 3\n      when temperature_min > 35.93 and temperature_min <= 36.39 then 2\n      when temperature_max >= 36.89 and temperature_max <= 39.88 then 2\n      else 0 end as temp_score\n,  case when UrineOutput is null then null\n      when UrineOutput < 671.09 then 10\n      when UrineOutput > 6896.80 then 8\n      when UrineOutput >= 671.09\n       and UrineOutput <= 1426.99 then 5\n      when UrineOutput >= 1427.00\n       and UrineOutput <= 2544.14 then 1\n      else 0 end as urineoutput_score\n,  case when mechvent is null then null\n      when mechvent = 1 then 9\n      else 0 end as mechvent_score\n,  case when electivesurgery is null then null\n      when electivesurgery = 1 then 0\n      else 6 end as electivesurgery_score\n\n\n-- The below code gives the component associated with each score\n
    -- This is not needed to calculate oasis, but provided for user convenience.\n-- If both the min/max are in the normal range (score of 0), then the average value is stored.\n, preiculos\n, age\n, gcs_min as gcs\n,  case when heart_rate_max is null then null\n      when heart_rate_max > 125 then heart_rate_max\n      when heart_rate_min < 33 then heart_rate_min\n      when heart_rate_max >= 107 and heart_rate_max <= 125 then heart_rate_max\n      when heart_rate_max >= 89 and heart_rate_max <= 106 then heart_rate_max\n      else (heart_rate_min+heart_rate_max)/2 end as heartrate\n,  case when mbp_min is null then null\n      when mbp_min < 20.65 then mbp_min\n      when mbp_min < 51 then mbp_min\n      when mbp_max > 143.44 then mbp_max\n      when mbp_min >= 51 and mbp_min < 61.33 then mbp_min\n      else (mbp_min+mbp_max)/2 end as meanbp\n,  case when resp_rate_min is null then null\n      when resp_rate_min <   6 then resp_rate_min\n      when resp_rate_max >  44 then resp_rate_max\n      when resp_rate_max >  30 then resp_rate_max\n      when resp_rate_max >  22 then resp_rate_max\n      when resp_rate_min <  13 then resp_rate_min\n      else (resp_rate_min+resp_rate_max)/2 end as resprate\n,  case when temperature_max is null then null\n      when temperature_max > 39.88 then temperature_max\n      when temperature_min >= 33.22 and temperature_min <= 35.93 then temperature_min\n      when temperature_max >= 33.22 and temperature_max <= 35.93 then temperature_max\n      when temperature_min < 33.22 then temperature_min\n      when temperature_min > 35.93 and temperature_min <= 36.39 then temperature_min\n      when temperature_max >= 36.89 and temperature_max <= 39.88 then temperature_max\n      else (temperature_min+temperature_max)/2 end as temp\n,  UrineOutput\n,  mechvent\n,  electivesurgery\nfrom cohort co\n)\n, score as\n(\nselect s.*\n    , coalesce(age_score,0)\n    + coalesce(preiculos_score,0)\n    + coalesce(gcs_score,0)\n    + coalesce(heart_rate_score,0)\n    + coalesce(mbp_score,0)\n    + coalesce(resp_rate_score,0)\n    + coalesce(temp_score,0)\n    + coalesce(urineoutput_score,0)\n    + coalesce(mechvent_score,0)\n    + coalesce(electivesurgery_score,0)\n    as oasis\nfrom scorecomp s\n)\nselect\n  subject_id, hadm_id, stay_id\n  , oasis\n  -- Calculate the probability of in-hospital mortality\n  , 1 / (1 + exp(- (-6.1746 + 0.1275*(oasis) ))) as oasis_prob\n  , age, age_score\n  , preiculos, preiculos_score\n  , gcs, gcs_score\n  , heartrate, heart_rate_score\n  , meanbp, mbp_score\n  , resprate, resp_rate_score\n  , temp, temp_score\n  , urineoutput, urineoutput_score\n  , mechvent, mechvent_score\n  , electivesurgery, electivesurgery_score\nfrom score\n;\n-- jing add tail\nalter table mimic4.score_oasis\nowner to postgres;"
sapsi <- "set search_path to mimic4;\ndrop materialized view if exists score_sapsii;\ncreate materialized view mimic4.score_sapsii\ntablespace pg_default\nas\n-- jing add head\nwith co as\n(\n    select \n        subject_id\n        , hadm_id\n        , stay_id\n        , intime AS starttime\n        , DATETIME_ADD(intime, interval '1 HOUR' * ('24')) AS endtime\n    from icustays ie\n)\n, cpap as\n(\n  select \n    co.subject_id\n    , co.stay_id\n    , GREATEST(min(DATETIME_SUB(charttime, interval '1 HOUR' * ('1'))), co.starttime) as starttime\n    , LEAST(max(DATETIME_ADD(charttime, interval '1 HOUR' * ('4'))), co.endtime) as endtime\n    , max(case when REGEXP_CONTAINS(lower(ce.value), '(cpap mask|bipap)') then 1 else 0 end) as cpap\n  from co\n  inner join chartevents ce\n    on co.stay_id = ce.stay_id\n    and ce.charttime > co.starttime\n    and ce.charttime <= co.endtime\n  where ce.itemid = 226732\n  and REGEXP_CONTAINS(lower(ce.value), '(cpap mask|bipap)')\n  group by co.subject_id, co.stay_id, co.starttime,co.endtime\n)\n\n-- extract a flag for surgical service\n-- this combined with \\\"elective\\\" from admissions table defines elective/non-elective surgery\n, surgflag as\n(\n  select adm.hadm_id\n    , case when lower(curr_service) like '%surg%' then 1 else 0 end as surgical\n    , ROW_NUMBER() over\n    (\n      PARTITION BY adm.HADM_ID\n      ORDER BY TRANSFERTIME\n    ) as serviceOrder\n  from admissions adm\n  left join services se\n    on adm.hadm_id = se.hadm_id\n)\n-- icd-9 diagnostic codes are our best source for comorbidity information\n-- unfortunately, they are technically a-causal\n-- however, this shouldn't matter too much for the SAPS II comorbidities\n, comorb as\n(\nselect hadm_id\n-- these are slightly different than elixhauser comorbidities, but based on them\n-- they include some non-comorbid ICD-9 codes (e.g. 20302, relapse of multiple myeloma)\n  , MAX(CASE\n    WHEN icd_version = 9 AND SUBSTR(icd_code, 1, 3) BETWEEN '042' AND '044'\n      THEN 1\n    WHEN icd_version = 10 AND SUBSTR(icd_code, 1, 3) BETWEEN 'B20' AND 'B22' THEN 1\n    WHEN icd_version = 10 AND SUBSTR(icd_code, 1, 3) = 'B24' THEN 1\n  ELSE 0 END) AS aids  /* HIV and AIDS */\n  , MAX(\n    CASE WHEN icd_version = 9 THEN\n      CASE\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20000' AND '20238' THEN 1 -- lymphoma\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20240' AND '20248' THEN 1 -- leukemia\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20250' AND '20302' THEN 1 -- lymphoma\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20310' AND '20312' THEN 1 -- leukemia\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20302' AND '20382' THEN 1 -- lymphoma\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20400' AND '20522' THEN 1 -- chronic leukemia\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20580' AND '20702' THEN 1 -- other myeloid leukemia\n        WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20720' AND '20892' THEN 1 -- other myeloid leukemia\n        WHEN SUBSTR(icd_code, 1, 4) IN ('2386', '2733') then 1 -- lymphoma\n      ELSE 0 END\n    WHEN icd_version = 10 AND SUBSTR(icd_code, 1, 3) BETWEEN 'C81' AND 'C96' THEN 1\n  ELSE 0 END) as hem\n  , MAX(CASE\n    WHEN icd_version = 9 THEN\n      CASE\n      WHEN SUBSTR(icd_code, 1, 4) BETWEEN '1960' AND '1991' THEN 1\n      WHEN SUBSTR(icd_code, 1, 5) BETWEEN '20970' AND '20975' THEN 1\n      WHEN SUBSTR(icd_code, 1, 5) IN ('20979', '78951') THEN 1\n      ELSE 0 END\n    WHEN icd_version = 10 AND SUBSTR(icd_code, 1, 3) BETWEEN 'C77' AND 'C79' THEN 1\n    WHEN icd_version = 10 AND SUBSTR(icd_code, 1, 4) = 'C800' THEN 1\n    ELSE 0 END) as mets      /* Metastatic cancer */\n    from diagnoses_icd\n  group by hadm_id\n)\n\n, pafi1 as\n(\n
    -- join blood gas to ventilation durations to determine if patient was vent\n  -- also join to cpap table for the same purpose\n  select \n    co.stay_id\n  , bg.charttime\n  , pao2fio2ratio AS PaO2FiO2\n  , case when vd.stay_id is not null then 1 else 0 end as vent\n  , case when cp.subject_id is not null then 1 else 0 end as cpap\n  from co\n  LEFT JOIN measurement_bg bg\n    ON co.subject_id = bg.subject_id\n    AND bg.specimen_pred = 'ART.'\n    AND bg.charttime > co.starttime\n    AND bg.charttime <= co.endtime\n  left join treatment_ventilation vd\n    on co.stay_id = vd.stay_id\n    and bg.charttime > vd.starttime\n    and bg.charttime <= vd.endtime\n    and vd.ventilation_status = 'InvasiveVent'\n  left join cpap cp\n    on bg.subject_id = cp.subject_id\n    and bg.charttime > cp.starttime\n    and bg.charttime <= cp.endtime\n)\n, pafi2 as\n(\n  -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients*\n  select stay_id\n  , min(PaO2FiO2) as PaO2FiO2_vent_min\n  from pafi1\n  where vent = 1 or cpap = 1\n  group by stay_id\n)\n\n, gcs AS\n(\n    select co.stay_id\n    , MIN(gcs.gcs) AS mingcs\n    FROM co\n    left join measurement_gcs gcs\n    ON co.stay_id = gcs.stay_id\n    AND co.starttime < gcs.charttime\n    AND gcs.charttime <= co.endtime\n    GROUP BY co.stay_id\n)\n\n, vital AS \n(\n    SELECT \n        co.stay_id\n      , MIN(vital.heart_rate) AS heartrate_min\n      , MAX(vital.heart_rate) AS heartrate_max\n      , MIN(vital.sbp) AS sysbp_min\n      , MAX(vital.sbp) AS sysbp_max\n      , MIN(vital.temperature) AS tempc_min\n      , MAX(vital.temperature) AS tempc_max\n    FROM co\n    left join measurement_vitalsign vital\n      on co.subject_id = vital.subject_id\n      AND co.starttime < vital.charttime\n      AND co.endtime >= vital.charttime\n    GROUP BY co.stay_id\n)\n, uo AS\n(\n    SELECT \n        co.stay_id\n      , SUM(uo.urineoutput) as urineoutput\n    FROM co\n    left join measurement_urine_output uo\n      on co.stay_id = uo.stay_id\n      AND co.starttime < uo.charttime\n      AND co.endtime >= uo.charttime\n    GROUP BY co.stay_id\n)\n, labs AS\n(\n    SELECT \n        co.stay_id\n      , MIN(labs.bun) AS bun_min\n      , MAX(labs.bun) AS bun_max\n      , MIN(labs.potassium) AS potassium_min\n      , MAX(labs.potassium) AS potassium_max\n      , MIN(labs.sodium) AS sodium_min\n      , MAX(labs.sodium) AS sodium_max\n      , MIN(labs.bicarbonate) AS bicarbonate_min\n      , MAX(labs.bicarbonate) AS bicarbonate_max               \n    FROM co\n    left join measurement_chemistry labs\n      on co.subject_id = labs.subject_id\n      AND co.starttime < labs.charttime\n      AND co.endtime >= labs.charttime\n    group by co.stay_id\n)\n, cbc AS\n(\n    SELECT \n        co.stay_id\n      , MIN(cbc.wbc) AS wbc_min\n      , MAX(cbc.wbc) AS wbc_max  \n    FROM co\n    LEFT JOIN measurement_complete_blood_count cbc\n      ON co.subject_id = cbc.subject_id\n      AND co.starttime < cbc.charttime\n      AND co.endtime >= cbc.charttime\n    GROUP BY co.stay_id\n)\n, enz AS\n(\n    SELECT \n        co.stay_id\n      , MIN(enz.bilirubin_total) AS bilirubin_min\n      , MAX(enz.bilirubin_total) AS bilirubin_max  \n    FROM co\n    LEFT JOIN measurement_enzyme enz\n      ON co.subject_id = enz.subject_id\n      AND co.starttime < enz.charttime\n      AND co.endtime >= enz.charttime\n    GROUP BY co.stay_id\n)\n\n, cohort as\n(\nselect \n    ie.subject_id, ie.hadm_id, ie.stay_id\n      , ie.intime\n      , ie.outtime\n      , va.age\n      , co.starttime\n      , co.endtime\n    \n      , vital.heartrate_max\n      , vital.heartrate_min\n      , vital.sysbp_max\n      , vital.sysbp_min\n      , vital.tempc_max\n      , vital.tempc_min\n\n
    -- this value is non-null iff the patient is on vent/cpap\n      , pf.PaO2FiO2_vent_min\n\n      , uo.urineoutput\n\n      , labs.bun_min\n      , labs.bun_max\n      , cbc.wbc_min\n      , cbc.wbc_max\n      , labs.potassium_min\n      , labs.potassium_max\n      , labs.sodium_min\n      , labs.sodium_max\n      , labs.bicarbonate_min\n      , labs.bicarbonate_max\n    \n      , enz.bilirubin_min\n      , enz.bilirubin_max\n\n      , gcs.mingcs\n\n      , comorb.AIDS\n      , comorb.HEM\n      , comorb.METS\n\n      , case\n          when adm.ADMISSION_TYPE = 'ELECTIVE' and sf.surgical = 1\n            then 'ScheduledSurgical'\n          when adm.ADMISSION_TYPE != 'ELECTIVE' and sf.surgical = 1\n            then 'UnscheduledSurgical'\n          else 'Medical'\n        end as AdmissionType\n\n\nfrom icustays ie\ninner join admissions adm\n  on ie.hadm_id = adm.hadm_id\nLEFT JOIN demographics_age va\n  on ie.hadm_id = va.hadm_id\ninner join co\n  on ie.stay_id = co.stay_id\n    \n-- join to above views\nleft join pafi2 pf\n  on ie.stay_id = pf.stay_id\nleft join surgflag sf\n  on adm.hadm_id = sf.hadm_id and sf.serviceOrder = 1\nleft join comorb\n  on ie.hadm_id = comorb.hadm_id\n\n-- join to custom tables to get more data....\nleft join gcs gcs\n  on ie.stay_id = gcs.stay_id\nleft join vital\n  on ie.stay_id = vital.stay_id\nleft join uo\n  on ie.stay_id = uo.stay_id\nleft join labs\n  on ie.stay_id = labs.stay_id\nleft join cbc\n  on ie.stay_id = cbc.stay_id\nleft join enz\n  on ie.stay_id = enz.stay_id\n)\n, scorecomp as\n(\nselect\n  cohort.*\n
    -- Below code calculates the component scores needed for SAPS\n  , case\n      when age is null then null\n      when age <  40 then 0\n      when age <  60 then 7\n      when age <  70 then 12\n      when age <  75 then 15\n      when age <  80 then 16\n      when age >= 80 then 18\n    end as age_score\n\n  , case\n      when heartrate_max is null then null\n      when heartrate_min <   40 then 11\n      when heartrate_max >= 160 then 7\n      when heartrate_max >= 120 then 4\n      when heartrate_min  <  70 then 2\n      when  heartrate_max >= 70 and heartrate_max < 120\n        and heartrate_min >= 70 and heartrate_min < 120\n      then 0\n    end as hr_score\n\n  , case\n      when  sysbp_min is null then null\n      when  sysbp_min <   70 then 13\n      when  sysbp_min <  100 then 5\n      when  sysbp_max >= 200 then 2\n      when  sysbp_max >= 100 and sysbp_max < 200\n        and sysbp_min >= 100 and sysbp_min < 200\n        then 0\n    end as sysbp_score\n\n  , case\n      when tempc_max is null then null\n      when tempc_max >= 39.0 then 3\n      when tempc_min <  39.0 then 0\n    end as temp_score\n\n  , case\n      when PaO2FiO2_vent_min is null then null\n      when PaO2FiO2_vent_min <  100 then 11\n      when PaO2FiO2_vent_min <  200 then 9\n      when PaO2FiO2_vent_min >= 200 then 6\n    end as PaO2FiO2_score\n\n  , case\n      when UrineOutput is null then null\n      when UrineOutput <   500.0 then 11\n      when UrineOutput <  1000.0 then 4\n      when UrineOutput >= 1000.0 then 0\n    end as uo_score\n\n  , case\n      when bun_max is null then null\n      when bun_max <  28.0 then 0\n      when bun_max <  84.0 then 6\n      when bun_max >= 84.0 then 10\n    end as bun_score\n\n  , case\n      when wbc_max is null then null\n      when wbc_min <   1.0 then 12\n      when wbc_max >= 20.0 then 3\n      when wbc_max >=  1.0 and wbc_max < 20.0\n       and wbc_min >=  1.0 and wbc_min < 20.0\n        then 0\n    end as wbc_score\n\n  , case\n      when potassium_max is null then null\n      when potassium_min <  3.0 then 3\n      when potassium_max >= 5.0 then 3\n      when potassium_max >= 3.0 and potassium_max < 5.0\n       and potassium_min >= 3.0 and potassium_min < 5.0\n        then 0\n      end as potassium_score\n\n  , case\n      when sodium_max is null then null\n      when sodium_min  < 125 then 5\n      when sodium_max >= 145 then 1\n      when sodium_max >= 125 and sodium_max < 145\n       and sodium_min >= 125 and sodium_min < 145\n        then 0\n      end as sodium_score\n\n  , case\n      when bicarbonate_max is null then null\n      when bicarbonate_min <  15.0 then 5\n      when bicarbonate_min <  20.0 then 3\n      when bicarbonate_max >= 20.0\n       and bicarbonate_min >= 20.0\n          then 0\n      end as bicarbonate_score\n\n  , case\n      when bilirubin_max is null then null\n      when bilirubin_max  < 4.0 then 0\n      when bilirubin_max  < 6.0 then 4\n      when bilirubin_max >= 6.0 then 9\n      end as bilirubin_score\n\n   , case\n      when mingcs is null then null\n        when mingcs <  3 then null
    -- erroneous value/on trach\n        when mingcs <  6 then 26\n        when mingcs <  9 then 13\n        when mingcs < 11 then 7\n        when mingcs < 14 then 5\n        when mingcs >= 14\n         and mingcs <= 15\n          then 0\n        end as gcs_score\n\n    , case\n        when AIDS = 1 then 17\n        when HEM  = 1 then 10\n        when METS = 1 then 9\n        else 0\n      end as comorbidity_score\n\n    , case\n        when AdmissionType = 'ScheduledSurgical' then 0\n        when AdmissionType = 'Medical' then 6\n        when AdmissionType = 'UnscheduledSurgical' then 8\n        else null\n      end as admissiontype_score\n\nfrom cohort\n)\n-- Calculate SAPS II here so we can use it in the probability calculation below\n, score as\n(\n  select s.*\n  -- coalesce statements impute normal score of zero if data element is missing\n  , coalesce(age_score,0)\n  + coalesce(hr_score,0)\n  + coalesce(sysbp_score,0)\n  + coalesce(temp_score,0)\n  + coalesce(PaO2FiO2_score,0)\n  + coalesce(uo_score,0)\n  + coalesce(bun_score,0)\n  + coalesce(wbc_score,0)\n  + coalesce(potassium_score,0)\n  + coalesce(sodium_score,0)\n  + coalesce(bicarbonate_score,0)\n  + coalesce(bilirubin_score,0)\n  + coalesce(gcs_score,0)\n  + coalesce(comorbidity_score,0)\n  + coalesce(admissiontype_score,0)\n    as sapsii\n  from scorecomp s\n)\nselect s.subject_id, s.hadm_id, s.stay_id\n, s.starttime\n, s.endtime\n, sapsii\n, 1 / (1 + exp(- (-7.7631 + 0.0737*(SAPSII) + 0.9971*(ln(SAPSII + 1))) )) as sapsii_prob\n, age_score\n, hr_score\n, sysbp_score\n, temp_score\n, PaO2FiO2_score\n, uo_score\n, bun_score\n, wbc_score\n, potassium_score\n, sodium_score\n, bicarbonate_score\n, bilirubin_score\n, gcs_score\n, comorbidity_score\n, admissiontype_score\nfrom score s\n;\n-- jing add tail\nalter table mimic4.score_sapsii\nowner to postgres;"

sirs <- "set search_path to mimic4;\ndrop materialized view if exists score_sirs;\ncreate materialized view mimic4.score_sirs\ntablespace pg_default\nas\n-- jing add head\n-- Aggregate the components for the score\nwith scorecomp as\n(\nselect ie.stay_id\n  , v.temperature_min\n  , v.temperature_max\n  , v.heart_rate_max\n  , v.resp_rate_max\n  , bg.pco2_min AS paco2_min\n  , l.wbc_min\n  , l.wbc_max\n  , l.bands_max\nFROM icustays ie\nleft join firstday_first_day_bg_art bg\n on ie.stay_id = bg.stay_id\nleft join firstday_first_day_vitalsign v\n  on ie.stay_id = v.stay_id\nleft join firstday_first_day_lab l\n  on ie.stay_id = l.stay_id\n)\n, scorecalc as\n(\n  -- Calculate the final score\n  -- note that if the underlying data is missing, the component is null\n  -- eventually these are treated as 0 (normal), but knowing when data is missing is useful for debugging\n  select stay_id\n  , case\n      when temperature_min < 36.0 then 1\n      when temperature_max > 38.0 then 1\n      when temperature_min is null then null\n      else 0\n    end as temp_score\n  , case\n      when heart_rate_max > 90.0  then 1\n      when heart_rate_max is null then null\n      else 0\n    end as heart_rate_score\n  , case\n      when resp_rate_max > 20.0  then 1\n      when paco2_min < 32.0  then 1\n      when coalesce(resp_rate_max, paco2_min) is null then null\n      else 0\n    end as resp_score\n  , case\n      when wbc_min <  4.0  then 1\n      when wbc_max > 12.0  then 1\n      when bands_max > 10 then 1-- > 10% immature neurophils (band forms)\n      when coalesce(wbc_min, bands_max) is null then null\n      else 0\n    end as wbc_score\n  from scorecomp\n)\nselect\n  ie.subject_id, ie.hadm_id, ie.stay_id\n  -- Combine all the scores to get sofa\n  -- Impute 0 if the score is missing\n  , coalesce(temp_score,0)\n  + coalesce(heart_rate_score,0)\n  + coalesce(resp_score,0)\n  + coalesce(wbc_score,0)\n    as sirs\n  , temp_score, heart_rate_score, resp_score, wbc_score\nFROM icustays ie\nleft join scorecalc s\n  on ie.stay_id = s.stay_id;\n-- jing add tail\nalter table mimic4.score_sirs\nowner to postgres;"

sofa <- "set search_path to mimic4;\ndrop materialized view if exists score_sofa;\ncreate materialized view mimic4.score_sofa\ntablespace pg_default\nas\n-- jing add head\nWITH co AS\n(\n  select ih.stay_id, ie.hadm_id\n  , hr\n  -- start/endtime can be used to filter to values within this hour\n  , DATETIME_SUB(ih.endtime, interval '1 HOUR' * ('1')) AS starttime\n  , ih.endtime\n  from demographics_icustay_hourly ih\n  INNER JOIN icustays ie\n    ON ih.stay_id = ie.stay_id\n)\n, pafi as\n(\n  -- join blood gas to ventilation durations to determine if patient was vent\n  select ie.stay_id\n  , bg.charttime\n  -- because pafi has an interaction between vent/PaO2:FiO2, we need two columns for the score\n  -- it can happen that the lowest unventilated PaO2/FiO2 is 68, but the lowest ventilated PaO2/FiO2 is 120\n  -- in this case, the sofa score is 3, *not* 4.\n  , case when vd.stay_id is null then pao2fio2ratio else null end pao2fio2ratio_novent\n  , case when vd.stay_id is not null then pao2fio2ratio else null end pao2fio2ratio_vent\n  FROM icustays ie\n  inner join measurement_bg bg\n    on ie.subject_id = bg.subject_id\n  left join treatment_ventilation vd\n    on ie.stay_id = vd.stay_id\n    and bg.charttime >= vd.starttime\n    and bg.charttime <= vd.endtime\n    and vd.ventilation_status = 'InvasiveVent'\n  WHERE specimen_pred = 'ART.'\n)\n, vs AS\n(\n    \n  select co.stay_id, co.hr\n  -- vitals\n  , min(vs.mbp) as meanbp_min\n  from co\n  left join measurement_vitalsign vs\n    on co.stay_id = vs.stay_id\n    and co.starttime < vs.charttime\n    and co.endtime >= vs.charttime\n  group by co.stay_id, co.hr\n)\n, gcs AS\n(\n  select co.stay_id, co.hr\n  -- gcs\n  , min(gcs.gcs) as gcs_min\n  from co\n  left join measurement_gcs gcs\n    on co.stay_id = gcs.stay_id\n    and co.starttime < gcs.charttime\n    and co.endtime >= gcs.charttime\n  group by co.stay_id, co.hr\n)\n, bili AS\n(\n  select co.stay_id, co.hr\n  , max(enz.bilirubin_total) as bilirubin_max\n  from co\n  left join measurement_enzyme enz\n    on co.hadm_id = enz.hadm_id\n    and co.starttime < enz.charttime\n    and co.endtime >= enz.charttime\n  group by co.stay_id, co.hr\n)\n, cr AS\n(\n  select co.stay_id, co.hr\n  , max(chem.creatinine) as creatinine_max\n  from co\n  left join measurement_chemistry chem\n    on co.hadm_id = chem.hadm_id\n    and co.starttime < chem.charttime\n    and co.endtime >= chem.charttime\n  group by co.stay_id, co.hr\n)\n, plt AS\n(\n  select co.stay_id, co.hr\n  , min(cbc.platelet) as platelet_min\n  from co\n  left join measurement_complete_blood_count cbc\n    on co.hadm_id = cbc.hadm_id\n    and co.starttime < cbc.charttime\n    and co.endtime >= cbc.charttime\n  group by co.stay_id, co.hr\n)\n, pf AS\n(\n  select co.stay_id, co.hr\n  , min(pafi.pao2fio2ratio_novent) AS pao2fio2ratio_novent\n  , min(pafi.pao2fio2ratio_vent) AS pao2fio2ratio_vent\n  from co\n  -- bring in blood gases that occurred during this hour\n  left join pafi\n    on co.stay_id = pafi.stay_id\n    and co.starttime < pafi.charttime\n    and co.endtime  >= pafi.charttime\n  group by co.stay_id, co.hr\n)\n-- sum uo separately to prevent duplicating values\n, uo as\n(\n  select co.stay_id, co.hr\n  -- uo\n  , MAX(\n      CASE WHEN uo.uo_tm_24hr >= 22 AND uo.uo_tm_24hr <= 30\n          THEN uo.urineoutput_24hr / uo.uo_tm_24hr * 24\n  END) as uo_24hr\n  from co\n  left join measurement_urine_output_rate uo\n    on co.stay_id = uo.stay_id\n    and co.starttime < uo.charttime\n    and co.endtime >= uo.charttime\n  group by co.stay_id, co.hr\n)\n
    -- collapse vasopressors into 1 row per hour\n-- also ensures only 1 row per chart time\n, vaso AS\n(\n    SELECT \n        co.stay_id\n        , co.hr\n        , MAX(epi.vaso_rate) as rate_epinephrine\n        , MAX(nor.vaso_rate) as rate_norepinephrine\n        , MAX(dop.vaso_rate) as rate_dopamine\n        , MAX(dob.vaso_rate) as rate_dobutamine\n    FROM co\n    LEFT JOIN medication_epinephrine epi\n        on co.stay_id = epi.stay_id\n        and co.endtime > epi.starttime\n        and co.endtime <= epi.endtime\n    LEFT JOIN medication_norepinephrine nor\n        on co.stay_id = nor.stay_id\n        and co.endtime > nor.starttime\n        and co.endtime <= nor.endtime\n    LEFT JOIN medication_dopamine dop\n        on co.stay_id = dop.stay_id\n        and co.endtime > dop.starttime\n        and co.endtime <= dop.endtime\n    LEFT JOIN medication_dobutamine dob\n        on co.stay_id = dob.stay_id\n        and co.endtime > dob.starttime\n        and co.endtime <= dob.endtime\n    WHERE epi.stay_id IS NOT NULL\n    OR nor.stay_id IS NOT NULL\n    OR dop.stay_id IS NOT NULL\n    OR dob.stay_id IS NOT NULL\n    GROUP BY co.stay_id, co.hr\n)\n, scorecomp as\n(\n  select\n      co.stay_id\n    , co.hr\n    , co.starttime, co.endtime\n    , pf.pao2fio2ratio_novent\n    , pf.pao2fio2ratio_vent\n    , vaso.rate_epinephrine\n    , vaso.rate_norepinephrine\n    , vaso.rate_dopamine\n    , vaso.rate_dobutamine\n    , vs.meanbp_min\n    , gcs.gcs_min\n    -- uo\n    , uo.uo_24hr\n    -- labs\n    , bili.bilirubin_max\n    , cr.creatinine_max\n    , plt.platelet_min\n  from co\n  left join vs\n    on co.stay_id = vs.stay_id\n    and co.hr = vs.hr\n  left join gcs\n    on co.stay_id = gcs.stay_id\n    and co.hr = gcs.hr\n  left join bili\n    on co.stay_id = bili.stay_id\n    and co.hr = bili.hr\n  left join cr\n    on co.stay_id = cr.stay_id\n    and co.hr = cr.hr\n  left join plt\n    on co.stay_id = plt.stay_id\n    and co.hr = plt.hr\n  left join pf\n    on co.stay_id = pf.stay_id\n    and co.hr = pf.hr\n  left join uo\n    on co.stay_id = uo.stay_id\n    and co.hr = uo.hr\n  left join vaso\n    on co.stay_id = vaso.stay_id\n    and co.hr = vaso.hr\n)\n, scorecalc as\n(\n  -- Calculate the final score\n  -- note that if the underlying data is missing, the component is null\n  -- eventually these are treated as 0 (normal), but knowing when data is missing is useful for debugging\n  select scorecomp.*\n  -- Respiration\n  , case\n      when pao2fio2ratio_vent   < 100 then 4\n      when pao2fio2ratio_vent   < 200 then 3\n      when pao2fio2ratio_novent < 300 then 2\n      when pao2fio2ratio_vent   < 300 then 2\n      when pao2fio2ratio_novent < 400 then 1\n      when pao2fio2ratio_vent   < 400 then 1\n      when coalesce(pao2fio2ratio_vent, pao2fio2ratio_novent) is null then null\n      else 0\n    end as respiration\n\n  -- coagulation\n  , case\n      when platelet_min < 20  then 4\n      when platelet_min < 50  then 3\n      when platelet_min < 100 then 2\n      when platelet_min < 150 then 1\n      when platelet_min is null then null\n      else 0\n    end as coagulation\n\n  -- Liver\n  , case\n      -- Bilirubin checks in mg/dL\n        when bilirubin_max >= 12.0 then 4\n        when bilirubin_max >= 6.0  then 3\n        when bilirubin_max >= 2.0  then 2\n        when bilirubin_max >= 1.2  then 1\n        when bilirubin_max is null then null\n        else 0\n      end as liver\n\n
    -- Cardiovascular\n  , case\n      when rate_dopamine > 15 or rate_epinephrine >  0.1 or rate_norepinephrine >  0.1 then 4\n      when rate_dopamine >  5 or rate_epinephrine <= 0.1 or rate_norepinephrine <= 0.1 then 3\n      when rate_dopamine >  0 or rate_dobutamine > 0 then 2\n      when meanbp_min < 70 then 1\n      when coalesce(meanbp_min, rate_dopamine, rate_dobutamine, rate_epinephrine, rate_norepinephrine) is null then null\n      else 0\n    end as cardiovascular\n\n  -- Neurological failure (GCS)\n  , case\n      when (gcs_min >= 13 and gcs_min <= 14) then 1\n      when (gcs_min >= 10 and gcs_min <= 12) then 2\n      when (gcs_min >=  6 and gcs_min <=  9) then 3\n      when  gcs_min <   6 then 4\n      when  gcs_min is null then null\n      else 0\n    end as cns\n\n  -- Renal failure - high creatinine or low urine output\n  , case\n    when (creatinine_max >= 5.0) then 4\n    when uo_24hr < 200 then 4\n    when (creatinine_max >= 3.5 and creatinine_max < 5.0) then 3\n    when uo_24hr < 500 then 3\n    when (creatinine_max >= 2.0 and creatinine_max < 3.5) then 2\n    when (creatinine_max >= 1.2 and creatinine_max < 2.0) then 1\n    when coalesce (uo_24hr, creatinine_max) is null then null\n    else 0 \n  end as renal\n  from scorecomp\n)\n, score_final as\n(\n  select s.*\n    -- Combine all the scores to get sofa\n    -- Impute 0 if the score is missing\n   -- the window function takes the max over the last 24 hours\n    , coalesce(\n        MAX(respiration) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0) as respiration_24hours\n     , coalesce(\n         MAX(coagulation) OVER (PARTITION BY stay_id ORDER BY HR\n         ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n        ,0) as coagulation_24hours\n    , coalesce(\n        MAX(liver) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0) as liver_24hours\n    , coalesce(\n        MAX(cardiovascular) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0) as cardiovascular_24hours\n    , coalesce(\n        MAX(cns) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0) as cns_24hours\n    , coalesce(\n        MAX(renal) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0) as renal_24hours\n\n    -- sum together data for final sofa\n    , coalesce(\n        MAX(respiration) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n     + coalesce(\n         MAX(coagulation) OVER (PARTITION BY stay_id ORDER BY HR\n         ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n     + coalesce(\n        MAX(liver) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n     + coalesce(\n        MAX(cardiovascular) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n     + coalesce(\n        MAX(cns) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n     + coalesce(\n        MAX(renal) OVER (PARTITION BY stay_id ORDER BY HR\n        ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING)\n      ,0)\n    as sofa_24hours\n  from scorecalc s\n  WINDOW W as\n  (\n    PARTITION BY stay_id\n    ORDER BY hr\n    ROWS BETWEEN 23 PRECEDING AND 0 FOLLOWING\n  )\n)\nselect * from score_final\nwhere hr >= 0;\n-- jing add tail\nalter table mimic4.score_sofa\nowner to postgres;"
first_day_sofa <- "set search_path to mimic4;\ndrop materialized view if exists firstday_first_day_sofa;\ncreate materialized view mimic4.firstday_first_day_sofa\ntablespace pg_default\nas\n-- jing add head\nwith vaso_stg as\n(\n  select ie.stay_id, 'norepinephrine' AS treatment, vaso_rate as rate\n  FROM icustays ie\n  INNER JOIN medication_norepinephrine mv\n    ON ie.stay_id = mv.stay_id\n    AND mv.starttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND mv.starttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  UNION ALL\n  select ie.stay_id, 'epinephrine' AS treatment, vaso_rate as rate\n  FROM icustays ie\n  INNER JOIN medication_epinephrine mv\n    ON ie.stay_id = mv.stay_id\n    AND mv.starttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND mv.starttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  UNION ALL\n  select ie.stay_id, 'dobutamine' AS treatment, vaso_rate as rate\n  FROM icustays ie\n  INNER JOIN medication_dobutamine mv\n    ON ie.stay_id = mv.stay_id\n    AND mv.starttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND mv.starttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  UNION ALL\n  select ie.stay_id, 'dopamine' AS treatment, vaso_rate as rate\n  FROM icustays ie\n  INNER JOIN medication_dopamine mv\n    ON ie.stay_id = mv.stay_id\n    AND mv.starttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n    AND mv.starttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n)\n, vaso_mv AS\n(\n    SELECT\n    ie.stay_id\n    , max(CASE WHEN treatment = 'norepinephrine' THEN rate ELSE NULL END) as rate_norepinephrine\n    , max(CASE WHEN treatment = 'epinephrine' THEN rate ELSE NULL END) as rate_epinephrine\n    , max(CASE WHEN treatment = 'dopamine' THEN rate ELSE NULL END) as rate_dopamine\n    , max(CASE WHEN treatment = 'dobutamine' THEN rate ELSE NULL END) as rate_dobutamine\n  from icustays ie\n  LEFT JOIN vaso_stg v\n      ON ie.stay_id = v.stay_id\n  GROUP BY ie.stay_id\n)\n, pafi1 as\n(\n  -- join blood gas to ventilation durations to determine if patient was vent\n  select ie.stay_id, bg.charttime\n  , bg.pao2fio2ratio\n  , case when vd.stay_id is not null then 1 else 0 end as IsVent\n  from icustays ie\n  LEFT JOIN measurement_bg bg\n      ON ie.subject_id = bg.subject_id\n      AND bg.charttime >= DATETIME_SUB(ie.intime, interval '1 HOUR' * ('6'))\n      AND bg.charttime <= DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n  LEFT JOIN treatment_ventilation vd\n    ON ie.stay_id = vd.stay_id\n    AND bg.charttime >= vd.starttime\n    AND bg.charttime <= vd.endtime\n    AND vd.ventilation_status = 'InvasiveVent'\n)\n, pafi2 as\n(\n  -- because pafi has an interaction between vent/PaO2:FiO2, we need two columns for the score\n  -- it can happen that the lowest unventilated PaO2/FiO2 is 68, but the lowest ventilated PaO2/FiO2 is 120\n  -- in this case, the sofa score is 3, *not* 4.\n  select stay_id\n  , min(case when IsVent = 0 then pao2fio2ratio else null end) as PaO2FiO2_novent_min\n  , min(case when IsVent = 1 then pao2fio2ratio else null end) as PaO2FiO2_vent_min\n  from pafi1\n  group by stay_id\n)\n
    -- Aggregate the components for the score\n, scorecomp as\n(\nselect ie.stay_id\n  , v.mbp_min\n  , mv.rate_norepinephrine\n  , mv.rate_epinephrine\n  , mv.rate_dopamine\n  , mv.rate_dobutamine\n\n  , l.creatinine_max\n  , l.bilirubin_total_max as bilirubin_max\n  , l.platelets_min as platelet_min\n\n  , pf.PaO2FiO2_novent_min\n  , pf.PaO2FiO2_vent_min\n\n  , uo.UrineOutput\n\n  , gcs.gcs_min\nfrom icustays ie\nleft join vaso_mv mv\n  on ie.stay_id = mv.stay_id\nleft join pafi2 pf\n on ie.stay_id = pf.stay_id\nleft join firstday_first_day_vitalsign v\n  on ie.stay_id = v.stay_id\nleft join firstday_first_day_lab l\n  on ie.stay_id = l.stay_id\nleft join firstday_first_day_urine_output uo\n  on ie.stay_id = uo.stay_id\nleft join firstday_first_day_gcs gcs\n  on ie.stay_id = gcs.stay_id\n)\n, scorecalc as\n(\n  select stay_id\n  -- Respiration\n  , case\n      when PaO2FiO2_vent_min   < 100 then 4\n      when PaO2FiO2_vent_min   < 200 then 3\n      when PaO2FiO2_novent_min < 300 then 2\n      when PaO2FiO2_novent_min < 400 then 1\n      when coalesce(PaO2FiO2_vent_min, PaO2FiO2_novent_min) is null then null\n      else 0\n    end as respiration\n\n  -- coagulation\n  , case\n      when platelet_min < 20  then 4\n      when platelet_min < 50  then 3\n      when platelet_min < 100 then 2\n      when platelet_min < 150 then 1\n      when platelet_min is null then null\n      else 0\n    end as coagulation\n  -- Liver\n  , case\n      -- Bilirubin checks in mg/dL\n        when bilirubin_max >= 12.0 then 4\n        when bilirubin_max >= 6.0  then 3\n        when bilirubin_max >= 2.0  then 2\n        when bilirubin_max >= 1.2  then 1\n        when bilirubin_max is null then null\n        else 0\n      end as liver\n  -- Cardiovascular\n  , case\n      when rate_dopamine > 15 or rate_epinephrine >  0.1 or rate_norepinephrine >  0.1 then 4\n      when rate_dopamine >  5 or rate_epinephrine <= 0.1 or rate_norepinephrine <= 0.1 then 3\n      when rate_dopamine >  0 or rate_dobutamine > 0 then 2\n      when mbp_min < 70 then 1\n      when coalesce(mbp_min, rate_dopamine, rate_dobutamine, rate_epinephrine, rate_norepinephrine) is null then null\n      else 0\n    end as cardiovascular\n  -- Neurological failure (GCS)\n  , case\n      when (gcs_min >= 13 and gcs_min <= 14) then 1\n      when (gcs_min >= 10 and gcs_min <= 12) then 2\n      when (gcs_min >=  6 and gcs_min <=  9) then 3\n      when  gcs_min <   6 then 4\n      when  gcs_min is null then null\n  else 0 end\n    as cns\n  -- Renal failure - high creatinine or low urine output\n  , case\n    when (creatinine_max >= 5.0) then 4\n    when  UrineOutput < 200 then 4\n    when (creatinine_max >= 3.5 and creatinine_max < 5.0) then 3\n    when  UrineOutput < 500 then 3\n    when (creatinine_max >= 2.0 and creatinine_max < 3.5) then 2\n    when (creatinine_max >= 1.2 and creatinine_max < 2.0) then 1\n    when coalesce(UrineOutput, creatinine_max) is null then null\n  else 0 end\n    as renal\n  from scorecomp\n)\nselect ie.subject_id, ie.hadm_id, ie.stay_id\n  -- Combine all the scores to get sofa\n  -- Impute 0 if the score is missing\n  , coalesce(respiration,0)\n  + coalesce(coagulation,0)\n  + coalesce(liver,0)\n  + coalesce(cardiovascular,0)\n  + coalesce(cns,0)\n  + coalesce(renal,0)\n  as sofa\n, respiration\n, coagulation\n, liver\n, cardiovascular\n, cns\n, renal\nfrom icustays ie\nleft join scorecalc s\n  on ie.stay_id = s.stay_id\n;\n-- jing add tail\nalter table mimic4.firstday_first_day_sofa\nowner to postgres;"

# sepsis
suspicion_of_infection <- "set search_path to mimic4;\ndrop materialized view if exists sepsis_suspicion_of_infection;\ncreate materialized view mimic4.sepsis_suspicion_of_infection\ntablespace pg_default\nas\n-- jing add head\n-- note this duplicates prescriptions\n-- each ICU stay in the same hospitalization will get a copy of all prescriptions for that hospitalization\nWITH ab_tbl AS \n(\n  select\n      abx.subject_id, abx.hadm_id, abx.stay_id\n    , abx.antibiotic\n    , abx.starttime AS antibiotic_time\n    -- date is used to match microbiology cultures with only date available\n    , DATE_TRUNC('DAY', abx.starttime) AS antibiotic_date\n    , abx.stoptime AS antibiotic_stoptime\n    , ROW_NUMBER() OVER\n    (\n      PARTITION BY subject_id\n      ORDER BY starttime, stoptime, antibiotic\n    ) AS ab_id\n  from medication_antibiotic abx\n)\n, me as\n(\n  select micro_specimen_id\n    -- the following columns are identical for all rows of the same micro_specimen_id\n    -- these aggregates simply collapse duplicates down to 1 row\n    , MAX(subject_id) AS subject_id\n    , MAX(hadm_id) AS hadm_id\n    , CAST(MAX(chartdate) AS DATE) AS chartdate\n    , MAX(charttime) AS charttime\n    , MAX(spec_type_desc) AS spec_type_desc\n    , max(case when org_name is not null and org_name != '' then 1 else 0 end) as PositiveCulture\n  from microbiologyevents\n  group by micro_specimen_id\n)\n-- culture followed by an antibiotic\n, me_then_ab AS\n(\n  select\n    ab_tbl.subject_id\n    , ab_tbl.hadm_id\n    , ab_tbl.stay_id\n    , ab_tbl.ab_id\n    \n    , me72.micro_specimen_id\n    , coalesce(me72.charttime, CAST(me72.chartdate AS TIMESTAMP)) as last72_charttime\n    , me72.positiveculture as last72_positiveculture\n    , me72.spec_type_desc as last72_specimen\n\n    -- we will use this partition to select the earliest culture before this abx\n    -- this ensures each antibiotic is only matched to a single culture\n    -- and consequently we have 1 row per antibiotic\n    , ROW_NUMBER() OVER\n    (\n      PARTITION BY ab_tbl.subject_id, ab_tbl.ab_id\n      ORDER BY me72.chartdate, me72.charttime NULLS LAST\n    ) AS micro_seq\n  from ab_tbl\n
    -- abx taken after culture, but no more than 72 hours after\n  LEFT JOIN me me72\n    on ab_tbl.subject_id = me72.subject_id\n    and\n    (\n      (\n      -- if charttime is available, use it\n          me72.charttime is not null\n      and ab_tbl.antibiotic_time > me72.charttime\n      and ab_tbl.antibiotic_time <= DATETIME_ADD(me72.charttime, interval '1 HOUR' * (72)) \n      )\n      OR\n      (\n      -- if charttime is not available, use chartdate\n          me72.charttime is null\n      and antibiotic_date >= me72.chartdate\n      and antibiotic_date <= DATETIME_ADD(me72.chartdate, interval '1 DAY' * (3))\n      )\n    )\n)\n, ab_then_me AS\n(\n  select\n      ab_tbl.subject_id\n    , ab_tbl.hadm_id\n    , ab_tbl.stay_id\n    , ab_tbl.ab_id\n    , me24.micro_specimen_id\n    , COALESCE(me24.charttime, CAST(me24.chartdate AS TIMESTAMP)) as next24_charttime\n    , me24.positiveculture as next24_positiveculture\n    , me24.spec_type_desc as next24_specimen\n\t\n    -- we will use this partition to select the earliest culture before this abx\n    -- this ensures each antibiotic is only matched to a single culture\n    -- and consequently we have 1 row per antibiotic\n    , ROW_NUMBER() OVER\n    (\n      PARTITION BY ab_tbl.subject_id, ab_tbl.ab_id\n      ORDER BY me24.chartdate, me24.charttime NULLS LAST\n    ) AS micro_seq\n  from ab_tbl\n  -- culture in subsequent 24 hours\n  LEFT JOIN me me24\n    on ab_tbl.subject_id = me24.subject_id\n    and\n    (\n      (\n          -- if charttime is available, use it\n          me24.charttime is not null\n      and ab_tbl.antibiotic_time >= DATETIME_SUB(me24.charttime, interval '1 HOUR' * (24))  \n      and ab_tbl.antibiotic_time < me24.charttime\n      )\n      OR\n      (\n          -- if charttime is not available, use chartdate\n          me24.charttime is null\n      and ab_tbl.antibiotic_date >= DATETIME_SUB(me24.chartdate, interval '1 DAY' * (1))\n      and ab_tbl.antibiotic_date <= me24.chartdate\n      )\n    )\n)\nSELECT\nab_tbl.subject_id\n, ab_tbl.stay_id\n, ab_tbl.hadm_id\n, ab_tbl.ab_id\n, ab_tbl.antibiotic\n, ab_tbl.antibiotic_time\n\n, CASE\n  WHEN last72_specimen IS NULL AND next24_specimen IS NULL\n    THEN 0\n  ELSE 1 \n  END AS suspected_infection\n-- time of suspected infection:\n--    (1) the culture time (if before antibiotic)\n--    (2) or the antibiotic time (if before culture)\n, CASE\n  WHEN last72_specimen IS NULL AND next24_specimen IS NULL\n    THEN NULL\n  ELSE COALESCE(last72_charttime, antibiotic_time)\n  END AS suspected_infection_time\n\n, COALESCE(last72_charttime, next24_charttime) AS culture_time\n\n-- the specimen that was cultured\n, COALESCE(last72_specimen, next24_specimen) AS specimen\n\n-- whether the cultured specimen ended up being positive or not\n, COALESCE(last72_positiveculture, next24_positiveculture) AS positive_culture\n\nFROM ab_tbl\nLEFT JOIN ab_then_me ab2me\n    ON ab_tbl.subject_id = ab2me.subject_id\n    AND ab_tbl.ab_id = ab2me.ab_id\n    AND ab2me.micro_seq = 1\nLEFT JOIN me_then_ab me2ab\n    ON ab_tbl.subject_id = me2ab.subject_id\n    AND ab_tbl.ab_id = me2ab.ab_id\n    AND me2ab.micro_seq = 1\n;\n-- jing add tail\nalter table mimic4.sepsis_suspicion_of_infection\nowner to postgres;"
sepsis3 <- "set search_path to mimic4;\ndrop materialized view if exists sepsis_sepsis3;\ncreate materialized view mimic4.sepsis_sepsis3\ntablespace pg_default\nas\n-- jing add head\nWITH sofa AS\n(\n  SELECT stay_id\n    , starttime, endtime\n    , respiration_24hours as respiration\n    , coagulation_24hours as coagulation\n    , liver_24hours as liver\n    , cardiovascular_24hours as cardiovascular\n    , cns_24hours as cns\n    , renal_24hours as renal\n    , sofa_24hours as sofa_score\n  FROM score_sofa\n  WHERE sofa_24hours >= 2\n)\n, s1 as\n(\n  SELECT \n    soi.subject_id\n    , soi.stay_id\n    -- suspicion columns\n    , soi.ab_id\n    , soi.antibiotic\n    , soi.antibiotic_time\n    , soi.culture_time\n    , soi.suspected_infection\n    , soi.suspected_infection_time\n    , soi.specimen\n    , soi.positive_culture\n    -- sofa columns\n    , starttime, endtime\n    , respiration, coagulation, liver, cardiovascular, cns, renal\n    , sofa_score\n    , sofa_score >= 2 and suspected_infection = 1 as sepsis3\n    -- subselect to the earliest suspicion/antibiotic/SOFA row\n    , ROW_NUMBER() OVER\n    (\n        PARTITION BY soi.stay_id\n        ORDER BY suspected_infection_time, antibiotic_time, culture_time, endtime\n    ) AS rn_sus\n  FROM sepsis_suspicion_of_infection as soi\n  INNER JOIN sofa\n    ON soi.stay_id = sofa.stay_id \n    AND sofa.endtime >= DATETIME_SUB(soi.suspected_infection_time, interval '1 HOUR' * (48))\n    AND sofa.endtime <= DATETIME_ADD(soi.suspected_infection_time, interval '1 HOUR' * (24))\n  -- only include in-ICU rows\n  WHERE soi.stay_id is not null\n)\nSELECT \nsubject_id, stay_id\n-- note: there may be more than one antibiotic given at this time\n, antibiotic_time\n-- culture times may be dates, rather than times\n, culture_time\n, suspected_infection_time\n-- endtime is latest time at which the sofa score is valid\n, endtime as sofa_time\n, sofa_score\n, respiration, coagulation, liver, cardiovascular, cns, renal\n, sepsis3\nFROM s1\nWHERE rn_sus = 1;\n-- jing add tail\nalter table mimic4.sepsis_sepsis3\nowner to postgres;"

x = c(
    # demographics
    age,
    icustay_detail,
    icustay_times,
    icustay_hourly,
    # conorbidity
    charlson,
    # duration
    weight_durations,
    # measurement
    bg,
    blood_differential,
    cardiac_marker,
    chemistry,
    coagulation,
    complete_blood_count,
    creatinine_baseline,
    enzyme,
    gcs,
    height,
    icp,
    inflammation,
    oxygen_delivery,
    rhythm,
    urine_output,
    urine_output_rate,
    ventilator_setting,
    vitalsign,
    # medication
    antibiotic,
    dobutamine,
    dopamine,
    epinephrine,
    neuroblock,
    norepinephrine,
    phenylephrine,
    vasopressin,
    # treatment
    crrt,
    invasive_line,
    ventilation,
    rrt,
    # first_day
    first_day_bg,
    first_day_bg_art,
    first_day_gcs,
    first_day_height,
    first_day_lab,
    first_day_rrt,
    first_day_urine_output,
    first_day_vitalsign,
    first_day_weight,
    # organfailure
    kdigo_creatinine,
    kdigo_uo,
    kdigo_stages,
    meld,
    # score
    apsiii,
    lods,
    oasis,
    sapsi,
    sirs,
    sofa,
    first_day_sofa,
    # sepsis
    suspicion_of_infection,
    sepsis3
)

x.names=c('age',
          'icustay_detail',
          'icustay_times',
          'icustay_hourly',
          'charlson',
          'weight_durations',
          'bg',
          'blood_differential',
          'cardiac_marker',
          'chemistry',
          'coagulation',
          'complete_blood_count',
          'creatinine_baseline',
          'enzyme',
          'gcs',
          'height',
          'icp',
          'inflammation',
          'oxygen_delivery',
          'rhythm',
          'urine_output',
          'urine_output_rate',
          'ventilator_setting',
          'vitalsign',
          'antibiotic',
          'dobutamine',
          'dopamine',
          'epinephrine',
          'neuroblock',
          'norepinephrine',
          'phenylephrine',
          'vasopressin',
          'crrt',
          'invasive_line',
          'ventilation',
          'rrt',
          'first_day_bg',
          'first_day_bg_art',
          'first_day_gcs',
          'first_day_height',
          'first_day_lab',
          'first_day_rrt',
          'first_day_urine_output',
          'first_day_vitalsign',
          'first_day_weight',
          'kdigo_creatinine',
          'kdigo_uo',
          'kdigo_stages',
          'meld',
          'apsiii',
          'lods',
          'oasis',
          'sapsi',
          'sirs',
          'sofa',
          'first_day_sofa',
          'suspicion_of_infection',
          'sepsis3')

if (missing(conn)) conn=get('connect_MIMIC',envir = .GlobalEnv)
if (missing(range)) range=1:length(x)
for (i in range) {
    if (i==1){
        cat('\n')
        message('Start time: ',Sys.time())
        starttime = Sys.time()
    }
    cat(paste0(i,'.'),x.names[i],
        do::rep_n(' ',nchar(length(x))+max(nchar(x.names))-nchar(x.names[i]) + 3+2-nchar(i)))
    consume = system.time(DBI::dbGetQuery(conn = conn$con,statement =x[i]))
    # consume = system.time(1+1)
    cat(time_segment(consume[3]),'\n')
    if (i == length(x)){
        message('Total time:',time_segment(as.numeric(Sys.time())-as.numeric(starttime)),'\n')
        message('End time: ',Sys.time())
    }
}
}
yikeshu0611/mimicR documentation built on Dec. 23, 2021, 7:21 p.m.