├── concepts_PG_local ├── medication │ ├── dopamine_pg.sql │ ├── dobutamine_pg.sql │ ├── epinephrine_pg.sql │ ├── vasopressin_pg.sql │ ├── norepinephrine_pg.sql │ ├── phenylephrine_pg.sql │ └── neuroblock_pg.sql ├── Materialized_views │ ├── dobutamine_MV.sql │ ├── dopamine_MV.sql │ ├── epinephrine_MV.sql │ ├── norepinephrine_MV.sql │ ├── first_day_urine_output _mv.sql │ ├── first_day_rrt_mv.sql │ ├── icustay_times_mv.sql │ ├── urine_output_mv.sql │ ├── coagulation_mv.sql │ ├── first_day_vitalsign_mv.sql │ ├── height_mv.sql │ ├── first_day_gcs - mv.sql │ ├── age_MV.sql │ ├── complete_blood_count_mv.sql │ ├── enzyme_mv.sql │ ├── first_day_bg_art_mv.sql │ ├── kdigo_creatinine_MV.sql │ ├── chemistry_mv.sql │ ├── vitalsign_mv.sql │ ├── ventilator_setting_MV.sql │ ├── kdigo_uo_MV.sql │ ├── weight_durations_mv.sql │ ├── oxygen_delivery_MV.sql │ ├── urine_output_rate_mv.sql │ ├── gcs_mv.sql │ ├── blood_differential_mv.sql │ ├── ventilation_mv.sql │ ├── first_day_lab_mv.sql │ └── bg_pg_mv.sql ├── firstday │ ├── first_day_urine_output _pg.sql │ ├── first_day_rrt_pg.sql │ ├── first_day_weight_pg.sql │ ├── first_day_height_pg.sql │ ├── first_day_vitalsign_pg.sql │ ├── first_day_gcs_pg.sql │ ├── first_day_bg_pg.sql │ ├── first_day_bg_art_pg.sql │ ├── first_day_lab_pg.sql │ └── first_day_sofa_pg.sql ├── measurement │ ├── icp_pg.sql │ ├── inflammation_pg.sql │ ├── cardiac_marker_pg.sql │ ├── rhythm_pg.sql │ ├── urine_output_pg.sql │ ├── coagulation_pg.sql │ ├── height_pg.sql │ ├── complete_blood_count_pg.sql │ ├── enzyme_pg.sql │ ├── creatinine_baseline_pg.sql │ ├── chemistry_pg.sql │ ├── vitalsign_pg.sql │ ├── ventilator_setting_pg.sql │ ├── oxygen_delivery_pg.sql │ ├── urine_output_rate_pg.sql │ ├── gcs_pg.sql │ ├── blood_differential_pg.sql │ └── bg_pg.sql ├── demographics │ ├── icustay_times_pg.sql │ ├── age_pg.sql │ ├── icustay_detail_pg.sql │ ├── icu_stay_hourly_pg.sql │ └── weight_durations_pg.sql ├── organfailure │ ├── kdigo_creatinine_pg.sql │ ├── kdigo_stages_pg.sql │ ├── kdigo_uo_pg.sql │ └── meld_pg.sql ├── score │ ├── sirs_pg.sql │ └── lods_pg.sql ├── treatment │ ├── invasive_line_pg.sql │ ├── crrt_pg.sql │ └── ventilation_pg.sql └── sepsis │ └── suspicion_of_infection_pg.sql ├── LICENSE └── README.md /concepts_PG_local/medication/dopamine_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of dopamine administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 221662 -- dopamine -------------------------------------------------------------------------------- /concepts_PG_local/medication/dobutamine_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of dopamine administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 221653 -- dobutamine -------------------------------------------------------------------------------- /concepts_PG_local/medication/epinephrine_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of epinephrine administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 221289 -- epinephrine -------------------------------------------------------------------------------- /concepts_PG_local/medication/vasopressin_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of vasopressin administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 222315 -- vasopressin -------------------------------------------------------------------------------- /concepts_PG_local/medication/norepinephrine_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of norepinephrine administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 221906 -- norepinephrine -------------------------------------------------------------------------------- /concepts_PG_local/medication/phenylephrine_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of phenylephrine administration 2 | select 3 | stay_id, linkorderid 4 | , rate as vaso_rate 5 | , amount as vaso_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid = 221749 -- phenylephrine 10 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/dobutamine_MV.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of dobutmine administration 2 | CREATE MATERIALIZED VIEW mimiciv.dobutamine_mv AS 3 | 4 | select 5 | stay_id, linkorderid 6 | , rate as vaso_rate 7 | , amount as vaso_amount 8 | , starttime 9 | , endtime 10 | from mimic_icu.inputevents 11 | where itemid = 221653 -- dobutamine -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/dopamine_MV.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of dopamine administration 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.dopamine_mv AS 4 | 5 | select 6 | stay_id, linkorderid 7 | , rate as vaso_rate 8 | , amount as vaso_amount 9 | , starttime 10 | , endtime 11 | from mimic_icu.inputevents 12 | where itemid = 221662 -- dopamine -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/epinephrine_MV.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of epinephrine administration 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.epinephrine_mv AS 4 | 5 | select 6 | stay_id, linkorderid 7 | , rate as vaso_rate 8 | , amount as vaso_amount 9 | , starttime 10 | , endtime 11 | from mimic_icu.inputevents 12 | where itemid = 221289 -- epinephrine -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/norepinephrine_MV.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of norepinephrine administration 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.norepinephrine_mv AS 4 | 5 | select 6 | stay_id, linkorderid 7 | , rate as vaso_rate 8 | , amount as vaso_amount 9 | , starttime 10 | , endtime 11 | from mimic_icu.inputevents 12 | where itemid = 221906 -- norepinephrine -------------------------------------------------------------------------------- /concepts_PG_local/medication/neuroblock_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts dose+durations of neuromuscular blocking agents 2 | select 3 | stay_id, orderid 4 | , rate as drug_rate 5 | , amount as drug_amount 6 | , starttime 7 | , endtime 8 | from mimic_icu.inputevents 9 | where itemid in 10 | ( 11 | 222062 -- Vecuronium (664 rows, 154 infusion rows) 12 | , 221555 -- Cisatracurium (9334 rows, 8970 infusion rows) 13 | ) 14 | and rate is not null -- only continuous infusions -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_urine_output _pg.sql: -------------------------------------------------------------------------------- 1 | -- Total urine output over the first 24 hours in the ICU 2 | SELECT 3 | -- patient identifiers 4 | ie.subject_id 5 | , ie.stay_id 6 | , SUM(urineoutput) AS urineoutput 7 | FROM mimic_icu.icustays ie 8 | -- Join to the outputevents table to get urine output 9 | LEFT JOIN mimiciv.urine_output_mv uo 10 | ON ie.stay_id = uo.stay_id 11 | -- ensure the data occurs during the first day 12 | AND uo.charttime >= ie.intime 13 | AND uo.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 14 | GROUP BY ie.subject_id, ie.stay_id -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_rrt_pg.sql: -------------------------------------------------------------------------------- 1 | -- flag indicating if patients received dialysis during 2 | -- the first day of their ICU stay 3 | select 4 | ie.subject_id 5 | , ie.stay_id 6 | , MAX(dialysis_present) AS dialysis_present 7 | , MAX(dialysis_active) AS dialysis_active 8 | , STRING_AGG(DISTINCT dialysis_type, ', ') AS dialysis_type 9 | FROM mimic_icu.icustays ie 10 | LEFT JOIN mimiciv.rrt_mv rrt 11 | ON ie.stay_id = rrt.stay_id 12 | AND rrt.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 13 | AND rrt.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 14 | GROUP BY ie.subject_id, ie.stay_id 15 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/icp_pg.sql: -------------------------------------------------------------------------------- 1 | with ce as 2 | ( 3 | select 4 | ce.subject_id 5 | , ce.stay_id 6 | , ce.charttime 7 | -- TODO: handle high ICPs when monitoring two ICPs 8 | , case when valuenum > 0 and valuenum < 100 then valuenum else null end as icp 9 | FROM mimic_icu.chartevents ce 10 | -- exclude rows marked as error 11 | where ce.itemid in 12 | ( 13 | 220765 -- Intra Cranial Pressure -- 92306 14 | , 227989 -- Intra Cranial Pressure #2 -- 1052 15 | ) 16 | ) 17 | select 18 | ce.subject_id 19 | , ce.stay_id 20 | , ce.charttime 21 | , MAX(icp) as icp 22 | from ce 23 | group by ce.subject_id, ce.stay_id, ce.charttime 24 | ; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/inflammation_pg.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | MAX(subject_id) AS subject_id 3 | , MAX(hadm_id) AS hadm_id 4 | , MAX(charttime) AS charttime 5 | , le.specimen_id 6 | -- convert from itemid into a meaningful column 7 | , MAX(CASE WHEN itemid = 50889 THEN valuenum ELSE NULL END) AS crp 8 | -- , CAST(NULL AS NUMERIC) AS il6 9 | -- , CAST(NULL AS NUMERIC) AS procalcitonin 10 | FROM mimic_hosp.labevents le 11 | WHERE le.itemid IN 12 | ( 13 | 50889 -- crp 14 | -- 51652 -- high sensitivity CRP 15 | ) 16 | AND valuenum IS NOT NULL 17 | -- lab values cannot be 0 and cannot be negative 18 | AND valuenum > 0 19 | GROUP BY le.specimen_id 20 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_urine_output _mv.sql: -------------------------------------------------------------------------------- 1 | -- Total urine output over the first 24 hours in the ICU 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.first_day_urine_output_mv AS 4 | 5 | SELECT 6 | -- patient identifiers 7 | ie.subject_id 8 | , ie.stay_id 9 | , SUM(urineoutput) AS urineoutput 10 | FROM mimic_icu.icustays ie 11 | -- Join to the outputevents table to get urine output 12 | LEFT JOIN mimiciv.urine_output_mv uo 13 | ON ie.stay_id = uo.stay_id 14 | -- ensure the data occurs during the first day 15 | AND uo.charttime >= ie.intime 16 | AND uo.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 17 | GROUP BY ie.subject_id, ie.stay_id -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_rrt_mv.sql: -------------------------------------------------------------------------------- 1 | -- flag indicating if patients received dialysis during 2 | -- the first day of their ICU stay 3 | 4 | CREATE MATERIALIZED VIEW mimiciv.first_day_rrt_mv AS 5 | 6 | select 7 | ie.subject_id 8 | , ie.stay_id 9 | , MAX(dialysis_present) AS dialysis_present 10 | , MAX(dialysis_active) AS dialysis_active 11 | , STRING_AGG(DISTINCT dialysis_type, ', ') AS dialysis_type 12 | FROM mimic_icu.icustays ie 13 | LEFT JOIN mimiciv.rrt_mv rrt 14 | ON ie.stay_id = rrt.stay_id 15 | AND rrt.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 16 | AND rrt.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 17 | GROUP BY ie.subject_id, ie.stay_id 18 | -------------------------------------------------------------------------------- /concepts_PG_local/demographics/icustay_times_pg.sql: -------------------------------------------------------------------------------- 1 | -- create a table which has fuzzy boundaries on hospital admission 2 | -- involves first creating a lag/lead version of disch/admit time 3 | -- get first/last heart rate measurement during hospitalization for each stay_id 4 | WITH t1 AS 5 | ( 6 | select ce.stay_id 7 | , min(charttime) as intime_hr 8 | , max(charttime) as outtime_hr 9 | FROM mimic_icu.chartevents ce 10 | -- only look at heart rate 11 | where ce.itemid = 220045 12 | group by ce.stay_id 13 | ) 14 | -- add in subject_id/hadm_id 15 | select 16 | ie.subject_id, ie.hadm_id, ie.stay_id 17 | , t1.intime_hr 18 | , t1.outtime_hr 19 | FROM mimic_icu.icustays ie 20 | left join t1 21 | on ie.stay_id = t1.stay_id; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/icustay_times_mv.sql: -------------------------------------------------------------------------------- 1 | -- create a table which has fuzzy boundaries on hospital admission 2 | -- involves first creating a lag/lead version of disch/admit time 3 | -- get first/last heart rate measurement during hospitalization for each stay_id 4 | CREATE materialized view mimiciv.icustay_times_mv AS 5 | 6 | WITH t1 AS 7 | ( 8 | select ce.stay_id 9 | , min(charttime) as intime_hr 10 | , max(charttime) as outtime_hr 11 | FROM mimic_icu.chartevents ce 12 | -- only look at heart rate 13 | where ce.itemid = 220045 14 | group by ce.stay_id 15 | ) 16 | -- add in subject_id/hadm_id 17 | select 18 | ie.subject_id, ie.hadm_id, ie.stay_id 19 | , t1.intime_hr 20 | , t1.outtime_hr 21 | FROM mimic_icu.icustays ie 22 | left join t1 23 | on ie.stay_id = t1.stay_id; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/cardiac_marker_pg.sql: -------------------------------------------------------------------------------- 1 | -- begin query that extracts the data 2 | SELECT 3 | MAX(subject_id) AS subject_id 4 | , MAX(hadm_id) AS hadm_id 5 | , MAX(charttime) AS charttime 6 | , le.specimen_id 7 | -- convert from itemid into a meaningful column 8 | , MAX(CASE WHEN itemid = 51002 THEN value ELSE NULL END) AS troponin_i 9 | , MAX(CASE WHEN itemid = 51003 THEN value ELSE NULL END) AS troponin_t 10 | , MAX(CASE WHEN itemid = 50911 THEN valuenum ELSE NULL END) AS ck_mb 11 | FROM mimic_hosp.labevents le 12 | WHERE le.itemid IN 13 | ( 14 | -- 51002, -- Troponin I (troponin-I is not measured in MIMIC-IV) 15 | -- 52598, -- Troponin I, point of care, rare/poor quality 16 | 51003, -- Troponin T 17 | 50911 -- Creatinine Kinase, MB isoenzyme 18 | ) 19 | GROUP BY le.specimen_id 20 | ; 21 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/rhythm_pg.sql: -------------------------------------------------------------------------------- 1 | -- Heart rhythm related documentation 2 | select 3 | ce.subject_id 4 | , ce.charttime 5 | , MAX(case when itemid = 220048 THEN value ELSE NULL END) AS heart_rhythm 6 | , MAX(case when itemid = 224650 THEN value ELSE NULL END) AS ectopy_type 7 | , MAX(case when itemid = 224651 THEN value ELSE NULL END) AS ectopy_frequency 8 | , MAX(case when itemid = 226479 THEN value ELSE NULL END) AS ectopy_type_secondary 9 | , MAX(case when itemid = 226480 THEN value ELSE NULL END) AS ectopy_frequency_secondary 10 | FROM mimic_icu.chartevents ce 11 | where ce.stay_id IS NOT NULL 12 | and ce.itemid in 13 | ( 14 | 220048, -- Heart Rhythm 15 | 224650, -- Ectopy Type 1 16 | 224651, -- Ectopy Frequency 1 17 | 226479, -- Ectopy Type 2 18 | 226480 -- Ectopy Frequency 2 19 | ) 20 | GROUP BY ce.subject_id, ce.charttime 21 | ; 22 | -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_weight_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts weights for adult ICU patients on their first ICU day. 2 | -- It does *not* use any information after the first ICU day, as weight is 3 | -- sometimes used to monitor fluid balance. 4 | -- The MIMIC-III version used echodata but this isn't available in MIMIC-IV. 5 | SELECT 6 | ie.subject_id 7 | , ie.stay_id 8 | , AVG(CASE WHEN weight_type = 'admit' THEN ce.weight ELSE NULL END) AS weight_admit 9 | , AVG(ce.weight) AS weight 10 | , MIN(ce.weight) AS weight_min 11 | , MAX(ce.weight) AS weight_max 12 | FROM mimic_icu.icustays ie 13 | -- admission weight 14 | LEFT JOIN mimiciv.weight_durations_mv ce 15 | ON ie.stay_id = ce.stay_id 16 | -- we filter to weights documented during or before the 1st day 17 | AND ce.starttime <= DATE(ie.intime + INTERVAL '1 DAY') 18 | GROUP BY ie.subject_id, ie.stay_id 19 | ; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Brent Richards 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/urine_output_pg.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | select 4 | stay_id 5 | , charttime 6 | , sum(urineoutput) as urineoutput 7 | from 8 | ( 9 | select 10 | -- patient identifiers 11 | oe.stay_id 12 | , oe.charttime 13 | -- volumes associated with urine output ITEMIDs 14 | -- note we consider input of GU irrigant as a negative volume 15 | -- GU irrigant volume in usually has a corresponding volume out 16 | -- so the net is often 0, despite large irrigant volumes 17 | , case 18 | when oe.itemid = 227488 and oe.value > 0 then -1*oe.value 19 | else oe.value 20 | end as urineoutput 21 | from mimic_icu.outputevents oe 22 | where itemid in 23 | ( 24 | 226559, -- Foley 25 | 226560, -- Void 26 | 226561, -- Condom Cath 27 | 226584, -- Ileoconduit 28 | 226563, -- Suprapubic 29 | 226564, -- R Nephrostomy 30 | 226565, -- L Nephrostomy 31 | 226567, -- Straight Cath 32 | 226557, -- R Ureteral Stent 33 | 226558, -- L Ureteral Stent 34 | 227488, -- GU Irrigant Volume In 35 | 227489 -- GU Irrigant/Urine Volume Out 36 | ) 37 | ) uo 38 | group by stay_id, charttime 39 | ; 40 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/coagulation_pg.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | MAX(subject_id) AS subject_id 3 | , MAX(hadm_id) AS hadm_id 4 | , MAX(charttime) AS charttime 5 | , le.specimen_id 6 | -- convert from itemid into a meaningful column 7 | , MAX(CASE WHEN itemid = 51196 THEN valuenum ELSE NULL END) AS d_dimer 8 | , MAX(CASE WHEN itemid = 51214 THEN valuenum ELSE NULL END) AS fibrinogen 9 | , MAX(CASE WHEN itemid = 51297 THEN valuenum ELSE NULL END) AS thrombin 10 | , MAX(CASE WHEN itemid = 51237 THEN valuenum ELSE NULL END) AS inr 11 | , MAX(CASE WHEN itemid = 51274 THEN valuenum ELSE NULL END) AS pt 12 | , MAX(CASE WHEN itemid = 51275 THEN valuenum ELSE NULL END) AS ptt 13 | FROM mimic_hosp.labevents le 14 | WHERE le.itemid IN 15 | ( 16 | -- 51149, 52750, 52072, 52073 -- Bleeding Time, no data as of MIMIC-IV v0.4 17 | 51196, -- D-Dimer 18 | 51214, -- Fibrinogen 19 | -- 51280, 52893, -- Reptilase Time, no data as of MIMIC-IV v0.4 20 | -- 51281, 52161, -- Reptilase Time Control, no data as of MIMIC-IV v0.4 21 | 51297, -- thrombin 22 | 51237, -- INR 23 | 51274, -- PT 24 | 51275 -- PTT 25 | ) 26 | AND valuenum IS NOT NULL 27 | GROUP BY le.specimen_id 28 | ; 29 | -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_height_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts heights for adult ICU patients. 2 | -- It uses all information from the patient's first ICU day. 3 | -- This is done for consistency with other queries - it's not necessarily needed. 4 | -- Height is unlikely to change throughout a patient's stay. 5 | 6 | -- The MIMIC-III version used echo data, this is not available in MIMIC-IV v0.4 7 | WITH ce AS 8 | ( 9 | SELECT 10 | c.stay_id 11 | , AVG(valuenum) as Height_chart 12 | FROM mimic_icu.chartevents c 13 | INNER JOIN mimic_icu.icustays ie ON 14 | c.stay_id = ie.stay_id 15 | AND c.charttime BETWEEN DATE(ie.intime - INTERVAL '1 DAY') AND DATE(ie.intime + INTERVAL '1 DAY') 16 | WHERE c.valuenum IS NOT NULL 17 | AND c.itemid in (226730) -- height 18 | AND c.valuenum != 0 19 | GROUP BY c.stay_id 20 | ) 21 | SELECT 22 | ie.subject_id 23 | , ie.stay_id 24 | , ROUND(AVG(height), 2) AS height 25 | FROM mimic_icu.icustays ie 26 | LEFT JOIN mimiciv.height_mv ht 27 | ON ie.stay_id = ht.stay_id 28 | AND ht.charttime >= DATE(ie.intime - INTERVAL '6 HOUR') 29 | AND ht.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 30 | GROUP BY ie.subject_id, ie.stay_id; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/urine_output_mv.sql: -------------------------------------------------------------------------------- 1 | CREATE materialized view mimiciv.urine_output_mv AS 2 | 3 | select 4 | stay_id 5 | , charttime 6 | , sum(urineoutput) as urineoutput 7 | from 8 | ( 9 | select 10 | -- patient identifiers 11 | oe.stay_id 12 | , oe.charttime 13 | -- volumes associated with urine output ITEMIDs 14 | -- note we consider input of GU irrigant as a negative volume 15 | -- GU irrigant volume in usually has a corresponding volume out 16 | -- so the net is often 0, despite large irrigant volumes 17 | , case 18 | when oe.itemid = 227488 and oe.value > 0 then -1*oe.value 19 | else oe.value 20 | end as urineoutput 21 | from mimic_icu.outputevents oe 22 | where itemid in 23 | ( 24 | 226559, -- Foley 25 | 226560, -- Void 26 | 226561, -- Condom Cath 27 | 226584, -- Ileoconduit 28 | 226563, -- Suprapubic 29 | 226564, -- R Nephrostomy 30 | 226565, -- L Nephrostomy 31 | 226567, -- Straight Cath 32 | 226557, -- R Ureteral Stent 33 | 226558, -- L Ureteral Stent 34 | 227488, -- GU Irrigant Volume In 35 | 227489 -- GU Irrigant/Urine Volume Out 36 | ) 37 | ) uo 38 | group by stay_id, charttime 39 | ; 40 | -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_vitalsign_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query pivots vital signs and aggregates them 2 | -- for the first 24 hours of a patient's stay. 3 | SELECT 4 | ie.subject_id 5 | , ie.stay_id 6 | , MIN(heart_rate) AS heart_rate_min 7 | , MAX(heart_rate) AS heart_rate_max 8 | , AVG(heart_rate) AS heart_rate_mean 9 | , MIN(sbp) AS sbp_min 10 | , MAX(sbp) AS sbp_max 11 | , AVG(sbp) AS sbp_mean 12 | , MIN(dbp) AS dbp_min 13 | , MAX(dbp) AS dbp_max 14 | , AVG(dbp) AS dbp_mean 15 | , MIN(mbp) AS mbp_min 16 | , MAX(mbp) AS mbp_max 17 | , AVG(mbp) AS mbp_mean 18 | , MIN(resp_rate) AS resp_rate_min 19 | , MAX(resp_rate) AS resp_rate_max 20 | , AVG(resp_rate) AS resp_rate_mean 21 | , MIN(temperature) AS temperature_min 22 | , MAX(temperature) AS temperature_max 23 | , AVG(temperature) AS temperature_mean 24 | , MIN(spo2) AS spo2_min 25 | , MAX(spo2) AS spo2_max 26 | , AVG(spo2) AS spo2_mean 27 | , MIN(glucose) AS glucose_min 28 | , MAX(glucose) AS glucose_max 29 | , AVG(glucose) AS glucose_mean 30 | FROM mimic_icu.icustays ie 31 | LEFT JOIN mimiciv.vitalsign_mv ce 32 | ON ie.stay_id = ce.stay_id 33 | AND ce.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 34 | AND ce.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 35 | GROUP BY ie.subject_id, ie.stay_id; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/coagulation_mv.sql: -------------------------------------------------------------------------------- 1 | CREATE materialized view mimiciv.coagulation_mv AS 2 | 3 | SELECT 4 | MAX(subject_id) AS subject_id 5 | , MAX(hadm_id) AS hadm_id 6 | , MAX(charttime) AS charttime 7 | , le.specimen_id 8 | -- convert from itemid into a meaningful column 9 | , MAX(CASE WHEN itemid = 51196 THEN valuenum ELSE NULL END) AS d_dimer 10 | , MAX(CASE WHEN itemid = 51214 THEN valuenum ELSE NULL END) AS fibrinogen 11 | , MAX(CASE WHEN itemid = 51297 THEN valuenum ELSE NULL END) AS thrombin 12 | , MAX(CASE WHEN itemid = 51237 THEN valuenum ELSE NULL END) AS inr 13 | , MAX(CASE WHEN itemid = 51274 THEN valuenum ELSE NULL END) AS pt 14 | , MAX(CASE WHEN itemid = 51275 THEN valuenum ELSE NULL END) AS ptt 15 | FROM mimic_hosp.labevents le 16 | WHERE le.itemid IN 17 | ( 18 | -- 51149, 52750, 52072, 52073 -- Bleeding Time, no data as of MIMIC-IV v0.4 19 | 51196, -- D-Dimer 20 | 51214, -- Fibrinogen 21 | -- 51280, 52893, -- Reptilase Time, no data as of MIMIC-IV v0.4 22 | -- 51281, 52161, -- Reptilase Time Control, no data as of MIMIC-IV v0.4 23 | 51297, -- thrombin 24 | 51237, -- INR 25 | 51274, -- PT 26 | 51275 -- PTT 27 | ) 28 | AND valuenum IS NOT NULL 29 | GROUP BY le.specimen_id 30 | ; 31 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_vitalsign_mv.sql: -------------------------------------------------------------------------------- 1 | -- This query pivots vital signs and aggregates them 2 | -- for the first 24 hours of a patient's stay. 3 | 4 | CREATE MATERIALIZED VIEW mimiciv.first_day_vitalsign_mv AS 5 | 6 | SELECT 7 | ie.subject_id 8 | , ie.stay_id 9 | , MIN(heart_rate) AS heart_rate_min 10 | , MAX(heart_rate) AS heart_rate_max 11 | , AVG(heart_rate) AS heart_rate_mean 12 | , MIN(sbp) AS sbp_min 13 | , MAX(sbp) AS sbp_max 14 | , AVG(sbp) AS sbp_mean 15 | , MIN(dbp) AS dbp_min 16 | , MAX(dbp) AS dbp_max 17 | , AVG(dbp) AS dbp_mean 18 | , MIN(mbp) AS mbp_min 19 | , MAX(mbp) AS mbp_max 20 | , AVG(mbp) AS mbp_mean 21 | , MIN(resp_rate) AS resp_rate_min 22 | , MAX(resp_rate) AS resp_rate_max 23 | , AVG(resp_rate) AS resp_rate_mean 24 | , MIN(temperature) AS temperature_min 25 | , MAX(temperature) AS temperature_max 26 | , AVG(temperature) AS temperature_mean 27 | , MIN(spo2) AS spo2_min 28 | , MAX(spo2) AS spo2_max 29 | , AVG(spo2) AS spo2_mean 30 | , MIN(glucose) AS glucose_min 31 | , MAX(glucose) AS glucose_max 32 | , AVG(glucose) AS glucose_mean 33 | FROM mimic_icu.icustays ie 34 | LEFT JOIN mimiciv.vitalsign_mv ce 35 | ON ie.stay_id = ce.stay_id 36 | AND ce.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 37 | AND ce.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 38 | GROUP BY ie.subject_id, ie.stay_id; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/height_pg.sql: -------------------------------------------------------------------------------- 1 | -- prep height 2 | WITH ht_in AS 3 | ( 4 | SELECT 5 | c.subject_id, c.stay_id, c.charttime 6 | -- Ensure that all heights are in centimeters 7 | , ROUND(CAST(c.valuenum * 2.54 AS NUMERIC), 2) AS height 8 | , c.valuenum as height_orig 9 | FROM mimic_icu.chartevents c 10 | WHERE c.valuenum IS NOT NULL 11 | -- Height (measured in inches) 12 | AND c.itemid = 226707 13 | ) 14 | , ht_cm AS 15 | ( 16 | SELECT 17 | c.subject_id, c.stay_id, c.charttime 18 | -- Ensure that all heights are in centimeters 19 | , ROUND(CAST(c.valuenum AS NUMERIC), 2) AS height 20 | FROM mimic_icu.chartevents c 21 | WHERE c.valuenum IS NOT NULL 22 | -- Height cm 23 | AND c.itemid = 226730 24 | ) 25 | -- merge cm/height, only take 1 value per charted row 26 | , ht_stg0 AS 27 | ( 28 | SELECT 29 | COALESCE(h1.subject_id, h1.subject_id) as subject_id 30 | , COALESCE(h1.stay_id, h1.stay_id) AS stay_id 31 | , COALESCE(h1.charttime, h1.charttime) AS charttime 32 | , COALESCE(h1.height, h2.height) as height 33 | FROM ht_cm h1 34 | FULL OUTER JOIN ht_in h2 35 | ON h1.subject_id = h2.subject_id 36 | AND h1.charttime = h2.charttime 37 | ) 38 | SELECT subject_id, stay_id, charttime, height 39 | FROM ht_stg0 40 | WHERE height IS NOT NULL 41 | -- filter out bad heights 42 | AND height > 120 AND height < 230; -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_gcs_pg.sql: -------------------------------------------------------------------------------- 1 | -- Glasgow Coma Scale, a measure of neurological function. 2 | -- Ranges from 3 (worst, comatose) to 15 (best, normal function). 3 | 4 | -- Note: 5 | -- The GCS for sedated patients is defaulted to 15 in this code. 6 | -- This follows common practice for scoring patients with severity of illness scores. 7 | -- 8 | -- e.g., from the SAPS II publication: 9 | -- For sedated patients, the Glasgow Coma Score before sedation was used. 10 | -- This was ascertained either from interviewing the physician who ordered the sedation, 11 | -- or by reviewing the patient's medical record. 12 | 13 | WITH gcs_final AS 14 | ( 15 | SELECT 16 | gcs.* 17 | -- This sorts the data by GCS 18 | -- rn = 1 is the the lowest total GCS value 19 | , ROW_NUMBER () OVER 20 | ( 21 | PARTITION BY gcs.stay_id 22 | ORDER BY gcs.GCS 23 | ) as gcs_seq 24 | FROM mimiciv.gcs_mv gcs 25 | ) 26 | SELECT 27 | ie.subject_id 28 | , ie.stay_id 29 | -- The minimum GCS is determined by the above row partition 30 | -- we only join if gcs_seq = 1 31 | , gcs AS gcs_min 32 | , gcs_motor 33 | , gcs_verbal 34 | , gcs_eyes 35 | , gcs_unable 36 | FROM mimic_icu.icustays ie 37 | LEFT JOIN gcs_final gs 38 | ON ie.stay_id = gs.stay_id 39 | AND gs.gcs_seq = 1 40 | ; 41 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/height_mv.sql: -------------------------------------------------------------------------------- 1 | -- prep height 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.height_mv AS 4 | 5 | WITH ht_in AS 6 | ( 7 | SELECT 8 | c.subject_id, c.stay_id, c.charttime 9 | -- Ensure that all heights are in centimeters 10 | , ROUND(CAST(c.valuenum * 2.54 AS NUMERIC), 2) AS height 11 | , c.valuenum as height_orig 12 | FROM mimic_icu.chartevents c 13 | WHERE c.valuenum IS NOT NULL 14 | -- Height (measured in inches) 15 | AND c.itemid = 226707 16 | ) 17 | , ht_cm AS 18 | ( 19 | SELECT 20 | c.subject_id, c.stay_id, c.charttime 21 | -- Ensure that all heights are in centimeters 22 | , ROUND(CAST(c.valuenum AS NUMERIC), 2) AS height 23 | FROM mimic_icu.chartevents c 24 | WHERE c.valuenum IS NOT NULL 25 | -- Height cm 26 | AND c.itemid = 226730 27 | ) 28 | -- merge cm/height, only take 1 value per charted row 29 | , ht_stg0 AS 30 | ( 31 | SELECT 32 | COALESCE(h1.subject_id, h1.subject_id) as subject_id 33 | , COALESCE(h1.stay_id, h1.stay_id) AS stay_id 34 | , COALESCE(h1.charttime, h1.charttime) AS charttime 35 | , COALESCE(h1.height, h2.height) as height 36 | FROM ht_cm h1 37 | FULL OUTER JOIN ht_in h2 38 | ON h1.subject_id = h2.subject_id 39 | AND h1.charttime = h2.charttime 40 | ) 41 | SELECT subject_id, stay_id, charttime, height 42 | FROM ht_stg0 43 | WHERE height IS NOT NULL 44 | -- filter out bad heights 45 | AND height > 120 AND height < 230; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_gcs - mv.sql: -------------------------------------------------------------------------------- 1 | -- Glasgow Coma Scale, a measure of neurological function. 2 | -- Ranges from 3 (worst, comatose) to 15 (best, normal function). 3 | 4 | -- Note: 5 | -- The GCS for sedated patients is defaulted to 15 in this code. 6 | -- This follows common practice for scoring patients with severity of illness scores. 7 | -- 8 | -- e.g., from the SAPS II publication: 9 | -- For sedated patients, the Glasgow Coma Score before sedation was used. 10 | -- This was ascertained either from interviewing the physician who ordered the sedation, 11 | -- or by reviewing the patient's medical record. 12 | 13 | CREATE MATERIALIZED VIEW mimiciv.first_day_gcs_mv AS 14 | 15 | WITH gcs_final AS 16 | ( 17 | SELECT 18 | gcs.* 19 | -- This sorts the data by GCS 20 | -- rn = 1 is the the lowest total GCS value 21 | , ROW_NUMBER () OVER 22 | ( 23 | PARTITION BY gcs.stay_id 24 | ORDER BY gcs.GCS 25 | ) as gcs_seq 26 | FROM mimiciv.gcs_mv gcs 27 | ) 28 | SELECT 29 | ie.subject_id 30 | , ie.stay_id 31 | -- The minimum GCS is determined by the above row partition 32 | -- we only join if gcs_seq = 1 33 | , gcs AS gcs_min 34 | , gcs_motor 35 | , gcs_verbal 36 | , gcs_eyes 37 | , gcs_unable 38 | FROM mimic_icu.icustays ie 39 | LEFT JOIN gcs_final gs 40 | ON ie.stay_id = gs.stay_id 41 | AND gs.gcs_seq = 1 42 | ; 43 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/complete_blood_count_pg.sql: -------------------------------------------------------------------------------- 1 | -- begin query that extracts the data 2 | SELECT 3 | MAX(subject_id) AS subject_id 4 | , MAX(hadm_id) AS hadm_id 5 | , MAX(charttime) AS charttime 6 | , le.specimen_id 7 | -- convert from itemid into a meaningful column 8 | , MAX(CASE WHEN itemid = 51221 THEN valuenum ELSE NULL END) AS hematocrit 9 | , MAX(CASE WHEN itemid = 51222 THEN valuenum ELSE NULL END) AS hemoglobin 10 | , MAX(CASE WHEN itemid = 51248 THEN valuenum ELSE NULL END) AS mch 11 | , MAX(CASE WHEN itemid = 51249 THEN valuenum ELSE NULL END) AS mchc 12 | , MAX(CASE WHEN itemid = 51250 THEN valuenum ELSE NULL END) AS mcv 13 | , MAX(CASE WHEN itemid = 51265 THEN valuenum ELSE NULL END) AS platelet 14 | , MAX(CASE WHEN itemid = 51279 THEN valuenum ELSE NULL END) AS rbc 15 | , MAX(CASE WHEN itemid = 51277 THEN valuenum ELSE NULL END) AS rdw 16 | , MAX(CASE WHEN itemid = 52159 THEN valuenum ELSE NULL END) AS rdwsd 17 | , MAX(CASE WHEN itemid = 51301 THEN valuenum ELSE NULL END) AS wbc 18 | FROM mimic_hosp.labevents le 19 | WHERE le.itemid IN 20 | ( 21 | 51221, -- hematocrit 22 | 51222, -- hemoglobin 23 | 51248, -- MCH 24 | 51249, -- MCHC 25 | 51250, -- MCV 26 | 51265, -- platelets 27 | 51279, -- RBC 28 | 51277, -- RDW 29 | 52159, -- RDW SD 30 | 51301 -- WBC 31 | 32 | ) 33 | AND valuenum IS NOT NULL 34 | -- lab values cannot be 0 and cannot be negative 35 | AND valuenum > 0 36 | GROUP BY le.specimen_id 37 | ; 38 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/age_MV.sql: -------------------------------------------------------------------------------- 1 | -- This query calculates the age of a patient on admission to the hospital. 2 | 3 | -- The columns of the table patients: anchor_age, anchor_year, anchor_year_group 4 | -- provide information regarding the actual patient year for the patient admission, 5 | -- and the patient's age at that time. 6 | 7 | -- anchor_year is a shifted year for the patient. 8 | -- anchor_year_group is a range of years - the patient's anchor_year occurred during this range. 9 | -- anchor_age is the patient's age in the anchor_year. 10 | -- Example: a patient has an anchor_year of 2153, 11 | -- anchor_year_group of 2008 - 2010, and an anchor_age of 60. 12 | -- The year 2153 for the patient corresponds to 2008, 2009, or 2010. 13 | -- The patient was 60 in the shifted year of 2153, i.e. they were 60 in 2008, 2009, or 2010. 14 | -- A patient admission in 2154 will occur in 2009-2011, 15 | -- an admission in 2155 will occur in 2010-2012, and so on. 16 | 17 | -- Therefore, the age of a patient = hospital admission time - anchor_year + anchor_age 18 | 19 | CREATE MATERIALIZED VIEW mimiciv.age_mv AS 20 | 21 | SELECT 22 | ad.subject_id 23 | , ad.hadm_id 24 | , ad.admittime 25 | , pa.anchor_age 26 | , pa.anchor_year 27 | , (date_part('year', ad.admittime) - pa.anchor_year) + pa.anchor_age AS age 28 | -- , DATETIME_DIFF(ad.admittime, DATETIME(pa.anchor_year, 1, 1, 0, 0, 0), YEAR) + pa.anchor_age AS age 29 | FROM mimic_core.admissions ad 30 | INNER JOIN mimic_core.patients pa 31 | ON ad.subject_id = pa.subject_id 32 | ; -------------------------------------------------------------------------------- /concepts_PG_local/demographics/age_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query calculates the age of a patient on admission to the hospital. 2 | 3 | -- The columns of the table patients: anchor_age, anchor_year, anchor_year_group 4 | -- provide information regarding the actual patient year for the patient admission, 5 | -- and the patient's age at that time. 6 | 7 | -- anchor_year is a shifted year for the patient. 8 | -- anchor_year_group is a range of years - the patient's anchor_year occurred during this range. 9 | -- anchor_age is the patient's age in the anchor_year. 10 | -- Example: a patient has an anchor_year of 2153, 11 | -- anchor_year_group of 2008 - 2010, and an anchor_age of 60. 12 | -- The year 2153 for the patient corresponds to 2008, 2009, or 2010. 13 | -- The patient was 60 in the shifted year of 2153, i.e. they were 60 in 2008, 2009, or 2010. 14 | -- A patient admission in 2154 will occur in 2009-2011, 15 | -- an admission in 2155 will occur in 2010-2012, and so on. 16 | 17 | -- Therefore, the age of a patient = hospital admission time - anchor_year + anchor_age 18 | SELECT 19 | ad.subject_id 20 | , ad.hadm_id 21 | , ad.admittime 22 | , pa.anchor_age 23 | , pa.anchor_year 24 | -- , EXTRACT(EPOCH FROM ad.admittime - pa.anchor_year )/365.242*24*3600 + pa.anchor_age AS age 25 | , (date_part('year', ad.admittime) - pa.anchor_year ) + pa.anchor_age AS age 26 | -- , DATETIME_DIFF(ad.admittime, DATETIME(pa.anchor_year, 1, 1, 0, 0, 0), YEAR) + pa.anchor_age AS age 27 | FROM mimic_core.admissions ad 28 | INNER JOIN mimic_core.patients pa 29 | ON ad.subject_id = pa.subject_id 30 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/complete_blood_count_mv.sql: -------------------------------------------------------------------------------- 1 | -- begin query that extracts the data 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.complete_blood_count_mv AS 4 | 5 | SELECT 6 | MAX(subject_id) AS subject_id 7 | , MAX(hadm_id) AS hadm_id 8 | , MAX(charttime) AS charttime 9 | , le.specimen_id 10 | -- convert from itemid into a meaningful column 11 | , MAX(CASE WHEN itemid = 51221 THEN valuenum ELSE NULL END) AS hematocrit 12 | , MAX(CASE WHEN itemid = 51222 THEN valuenum ELSE NULL END) AS hemoglobin 13 | , MAX(CASE WHEN itemid = 51248 THEN valuenum ELSE NULL END) AS mch 14 | , MAX(CASE WHEN itemid = 51249 THEN valuenum ELSE NULL END) AS mchc 15 | , MAX(CASE WHEN itemid = 51250 THEN valuenum ELSE NULL END) AS mcv 16 | , MAX(CASE WHEN itemid = 51265 THEN valuenum ELSE NULL END) AS platelet 17 | , MAX(CASE WHEN itemid = 51279 THEN valuenum ELSE NULL END) AS rbc 18 | , MAX(CASE WHEN itemid = 51277 THEN valuenum ELSE NULL END) AS rdw 19 | , MAX(CASE WHEN itemid = 52159 THEN valuenum ELSE NULL END) AS rdwsd 20 | , MAX(CASE WHEN itemid = 51301 THEN valuenum ELSE NULL END) AS wbc 21 | FROM mimic_hosp.labevents le 22 | WHERE le.itemid IN 23 | ( 24 | 51221, -- hematocrit 25 | 51222, -- hemoglobin 26 | 51248, -- MCH 27 | 51249, -- MCHC 28 | 51250, -- MCV 29 | 51265, -- platelets 30 | 51279, -- RBC 31 | 51277, -- RDW 32 | 52159, -- RDW SD 33 | 51301 -- WBC 34 | 35 | ) 36 | AND valuenum IS NOT NULL 37 | -- lab values cannot be 0 and cannot be negative 38 | AND valuenum > 0 39 | GROUP BY le.specimen_id 40 | ; 41 | -------------------------------------------------------------------------------- /concepts_PG_local/demographics/icustay_detail_pg.sql: -------------------------------------------------------------------------------- 1 | SELECT ie.subject_id, ie.hadm_id, ie.stay_id 2 | 3 | -- patient level factors 4 | , pat.gender, pat.dod 5 | 6 | -- hospital level factors 7 | , adm.admittime, adm.dischtime 8 | , adm.dischtime::DATE - adm.admittime::DATE as los_hospital 9 | --, DATETIME_DIFF(adm.dischtime, adm.admittime, DAY) as los_hospital 10 | --, DATETIME_DIFF(adm.admittime, DATETIME(pat.anchor_year, 1, 1, 0, 0, 0), YEAR) + pat.anchor_age as admission_age 11 | , (date_part('year', adm.admittime) - pat.anchor_year) + pat.anchor_age AS admission_age 12 | , adm.ethnicity 13 | , adm.hospital_expire_flag 14 | , DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) AS hospstay_seq 15 | , CASE 16 | WHEN DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) = 1 THEN True 17 | ELSE False END AS first_hosp_stay 18 | 19 | -- icu level factors 20 | , ie.intime as icu_intime, ie.outtime as icu_outtime 21 | , ROUND(cast(extract (EPOCH FROM (ie.outtime - ie.intime)/3600) as numeric), 2) as los_icu 22 | 23 | --, age(ie.outtime, ie.intime) as los_icu --works, but long time 24 | --, ROUND(DATETIME_DIFF(ie.outtime, ie.intime, HOUR)/24.0, 2) as los_icu 25 | , DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) AS icustay_seq 26 | 27 | -- first ICU stay *for the current hospitalization* 28 | , CASE 29 | WHEN DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) = 1 THEN True 30 | ELSE False END AS first_icu_stay 31 | 32 | FROM mimic_icu.icustays ie 33 | INNER JOIN mimic_core.admissions adm 34 | ON ie.hadm_id = adm.hadm_id 35 | INNER JOIN mimic_core.patients pat 36 | ON ie.subject_id = pat.subject_id 37 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/enzyme_pg.sql: -------------------------------------------------------------------------------- 1 | -- begin query that extracts the data 2 | SELECT 3 | MAX(subject_id) AS subject_id 4 | , MAX(hadm_id) AS hadm_id 5 | , MAX(charttime) AS charttime 6 | , le.specimen_id 7 | -- convert from itemid into a meaningful column 8 | , MAX(CASE WHEN itemid = 50861 THEN valuenum ELSE NULL END) AS alt 9 | , MAX(CASE WHEN itemid = 50863 THEN valuenum ELSE NULL END) AS alp 10 | , MAX(CASE WHEN itemid = 50878 THEN valuenum ELSE NULL END) AS ast 11 | , MAX(CASE WHEN itemid = 50867 THEN valuenum ELSE NULL END) AS amylase 12 | , MAX(CASE WHEN itemid = 50885 THEN valuenum ELSE NULL END) AS bilirubin_total 13 | , MAX(CASE WHEN itemid = 50883 THEN valuenum ELSE NULL END) AS bilirubin_direct 14 | , MAX(CASE WHEN itemid = 50884 THEN valuenum ELSE NULL END) AS bilirubin_indirect 15 | , MAX(CASE WHEN itemid = 50910 THEN valuenum ELSE NULL END) AS ck_cpk 16 | , MAX(CASE WHEN itemid = 50911 THEN valuenum ELSE NULL END) AS ck_mb 17 | , MAX(CASE WHEN itemid = 50927 THEN valuenum ELSE NULL END) AS ggt 18 | , MAX(CASE WHEN itemid = 50954 THEN valuenum ELSE NULL END) AS ld_ldh 19 | FROM mimic_hosp.labevents le 20 | WHERE le.itemid IN 21 | ( 22 | 50861, -- Alanine transaminase (ALT) 23 | 50863, -- Alkaline phosphatase (ALP) 24 | 50878, -- Aspartate transaminase (AST) 25 | 50867, -- Amylase 26 | 50885, -- total bili 27 | 50884, -- indirect bili 28 | 50883, -- direct bili 29 | 50910, -- ck_cpk 30 | 50911, -- CK-MB 31 | 50927, -- Gamma Glutamyltransferase (GGT) 32 | 50954 -- ld_ldh 33 | ) 34 | AND valuenum IS NOT NULL 35 | -- lab values cannot be 0 and cannot be negative 36 | AND valuenum > 0 37 | GROUP BY le.specimen_id 38 | ; 39 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/enzyme_mv.sql: -------------------------------------------------------------------------------- 1 | -- begin query that extracts the data 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.enzyme_mv AS 4 | 5 | SELECT 6 | MAX(subject_id) AS subject_id 7 | , MAX(hadm_id) AS hadm_id 8 | , MAX(charttime) AS charttime 9 | , le.specimen_id 10 | -- convert from itemid into a meaningful column 11 | , MAX(CASE WHEN itemid = 50861 THEN valuenum ELSE NULL END) AS alt 12 | , MAX(CASE WHEN itemid = 50863 THEN valuenum ELSE NULL END) AS alp 13 | , MAX(CASE WHEN itemid = 50878 THEN valuenum ELSE NULL END) AS ast 14 | , MAX(CASE WHEN itemid = 50867 THEN valuenum ELSE NULL END) AS amylase 15 | , MAX(CASE WHEN itemid = 50885 THEN valuenum ELSE NULL END) AS bilirubin_total 16 | , MAX(CASE WHEN itemid = 50883 THEN valuenum ELSE NULL END) AS bilirubin_direct 17 | , MAX(CASE WHEN itemid = 50884 THEN valuenum ELSE NULL END) AS bilirubin_indirect 18 | , MAX(CASE WHEN itemid = 50910 THEN valuenum ELSE NULL END) AS ck_cpk 19 | , MAX(CASE WHEN itemid = 50911 THEN valuenum ELSE NULL END) AS ck_mb 20 | , MAX(CASE WHEN itemid = 50927 THEN valuenum ELSE NULL END) AS ggt 21 | , MAX(CASE WHEN itemid = 50954 THEN valuenum ELSE NULL END) AS ld_ldh 22 | FROM mimic_hosp.labevents le 23 | WHERE le.itemid IN 24 | ( 25 | 50861, -- Alanine transaminase (ALT) 26 | 50863, -- Alkaline phosphatase (ALP) 27 | 50878, -- Aspartate transaminase (AST) 28 | 50867, -- Amylase 29 | 50885, -- total bili 30 | 50884, -- indirect bili 31 | 50883, -- direct bili 32 | 50910, -- ck_cpk 33 | 50911, -- CK-MB 34 | 50927, -- Gamma Glutamyltransferase (GGT) 35 | 50954 -- ld_ldh 36 | ) 37 | AND valuenum IS NOT NULL 38 | -- lab values cannot be 0 and cannot be negative 39 | AND valuenum > 0 40 | GROUP BY le.specimen_id 41 | ; 42 | -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_bg_pg.sql: -------------------------------------------------------------------------------- 1 | -- Highest/lowest blood gas values for all blood specimens (venous/arterial/mixed) 2 | select 3 | ie.subject_id 4 | , ie.stay_id 5 | , MIN(lactate) AS lactate_min, MAX(lactate) AS lactate_max 6 | , MIN(ph) AS ph_min, MAX(ph) AS ph_max 7 | , MIN(so2) AS so2_min, MAX(so2) AS so2_max 8 | , MIN(po2) AS po2_min, MAX(po2) AS po2_max 9 | , MIN(pco2) AS pco2_min, MAX(pco2) AS pco2_max 10 | , MIN(aado2) AS aado2_min, MAX(aado2) AS aado2_max 11 | , MIN(aado2_calc) AS aado2_calc_min, MAX(aado2_calc) AS aado2_calc_max 12 | , MIN(pao2fio2ratio) AS pao2fio2ratio_min, MAX(pao2fio2ratio) AS pao2fio2ratio_max 13 | , MIN(baseexcess) AS baseexcess_min, MAX(baseexcess) AS baseexcess_max 14 | , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max 15 | , MIN(totalco2) AS totalco2_min, MAX(totalco2) AS totalco2_max 16 | , MIN(hematocrit) AS hematocrit_min, MAX(hematocrit) AS hematocrit_max 17 | , MIN(hemoglobin) AS hemoglobin_min, MAX(hemoglobin) AS hemoglobin_max 18 | , MIN(carboxyhemoglobin) AS carboxyhemoglobin_min, MAX(carboxyhemoglobin) AS carboxyhemoglobin_max 19 | , MIN(methemoglobin) AS methemoglobin_min, MAX(methemoglobin) AS methemoglobin_max 20 | , MIN(temperature) AS temperature_min, MAX(temperature) AS temperature_max 21 | , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max 22 | , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max 23 | , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max 24 | , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max 25 | , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max 26 | FROM mimic_icu.icustays ie 27 | LEFT JOIN mimiciv.bg_mv bg 28 | ON ie.subject_id = bg.subject_id 29 | AND bg.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 30 | AND bg.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 31 | GROUP BY ie.subject_id, ie.stay_id 32 | ; -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_bg_art_pg.sql: -------------------------------------------------------------------------------- 1 | -- Highest/lowest blood gas values for arterial blood specimens 2 | select 3 | ie.subject_id 4 | , ie.stay_id 5 | , MIN(lactate) AS lactate_min, MAX(lactate) AS lactate_max 6 | , MIN(ph) AS ph_min, MAX(ph) AS ph_max 7 | , MIN(so2) AS so2_min, MAX(so2) AS so2_max 8 | , MIN(po2) AS po2_min, MAX(po2) AS po2_max 9 | , MIN(pco2) AS pco2_min, MAX(pco2) AS pco2_max 10 | , MIN(aado2) AS aado2_min, MAX(aado2) AS aado2_max 11 | , MIN(aado2_calc) AS aado2_calc_min, MAX(aado2_calc) AS aado2_calc_max 12 | , MIN(pao2fio2ratio) AS pao2fio2ratio_min, MAX(pao2fio2ratio) AS pao2fio2ratio_max 13 | , MIN(baseexcess) AS baseexcess_min, MAX(baseexcess) AS baseexcess_max 14 | , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max 15 | , MIN(totalco2) AS totalco2_min, MAX(totalco2) AS totalco2_max 16 | , MIN(hematocrit) AS hematocrit_min, MAX(hematocrit) AS hematocrit_max 17 | , MIN(hemoglobin) AS hemoglobin_min, MAX(hemoglobin) AS hemoglobin_max 18 | , MIN(carboxyhemoglobin) AS carboxyhemoglobin_min, MAX(carboxyhemoglobin) AS carboxyhemoglobin_max 19 | , MIN(methemoglobin) AS methemoglobin_min, MAX(methemoglobin) AS methemoglobin_max 20 | , MIN(temperature) AS temperature_min, MAX(temperature) AS temperature_max 21 | , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max 22 | , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max 23 | , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max 24 | , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max 25 | , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max 26 | FROM mimic_icu.icustays ie 27 | LEFT JOIN mimiciv.bg_mv bg 28 | ON ie.subject_id = bg.subject_id 29 | AND bg.specimen_pred = 'ART.' 30 | AND bg.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 31 | AND bg.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 32 | GROUP BY ie.subject_id, ie.stay_id 33 | ; -------------------------------------------------------------------------------- /concepts_PG_local/organfailure/kdigo_creatinine_pg.sql: -------------------------------------------------------------------------------- 1 | -- Extract all creatinine values from labevents around patient's ICU stay 2 | WITH cr AS 3 | ( 4 | SELECT 5 | ie.hadm_id 6 | , ie.stay_id 7 | , le.charttime 8 | , AVG(le.valuenum) AS creat 9 | FROM mimic_icu.icustays ie 10 | LEFT JOIN mimic_hosp.labevents le 11 | ON ie.subject_id = le.subject_id 12 | AND le.ITEMID = 50912 13 | AND le.VALUENUM IS NOT NULL 14 | AND le.VALUENUM <= 150 15 | AND le.CHARTTIME BETWEEN DATE(ie.intime - INTERVAL '7 DAYS') AND ie.outtime 16 | GROUP BY ie.hadm_id, ie.stay_id, le.charttime 17 | ) 18 | , cr48 AS 19 | ( 20 | -- add in the lowest value in the previous 48 hours 21 | SELECT 22 | cr.stay_id 23 | , cr.charttime 24 | , MIN(cr48.creat) AS creat_low_past_48hr 25 | FROM cr 26 | -- add in all creatinine values in the last 48 hours 27 | LEFT JOIN cr cr48 28 | ON cr.stay_id = cr48.stay_id 29 | AND cr48.charttime < cr.charttime 30 | AND cr48.charttime >= DATE(cr.charttime - INTERVAL '48 HOUR') 31 | GROUP BY cr.stay_id, cr.charttime 32 | ) 33 | , cr7 AS 34 | ( 35 | -- add in the lowest value in the previous 7 days 36 | SELECT 37 | cr.stay_id 38 | , cr.charttime 39 | , MIN(cr7.creat) AS creat_low_past_7day 40 | FROM cr 41 | -- add in all creatinine values in the last 7 days 42 | LEFT JOIN cr cr7 43 | ON cr.stay_id = cr7.stay_id 44 | AND cr7.charttime < cr.charttime 45 | AND cr7.charttime >= DATE(cr.charttime - INTERVAL '7 DAY') 46 | GROUP BY cr.stay_id, cr.charttime 47 | ) 48 | SELECT 49 | cr.hadm_id 50 | , cr.stay_id 51 | , cr.charttime 52 | , cr.creat 53 | , cr48.creat_low_past_48hr 54 | , cr7.creat_low_past_7day 55 | FROM cr 56 | LEFT JOIN cr48 57 | ON cr.stay_id = cr48.stay_id 58 | AND cr.charttime = cr48.charttime 59 | LEFT JOIN cr7 60 | ON cr.stay_id = cr7.stay_id 61 | AND cr.charttime = cr7.charttime 62 | ; 63 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_bg_art_mv.sql: -------------------------------------------------------------------------------- 1 | -- Highest/lowest blood gas values for arterial blood specimens 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.first_day_bg_art_mv AS 4 | 5 | select 6 | ie.subject_id 7 | , ie.stay_id 8 | , MIN(lactate) AS lactate_min, MAX(lactate) AS lactate_max 9 | , MIN(ph) AS ph_min, MAX(ph) AS ph_max 10 | , MIN(so2) AS so2_min, MAX(so2) AS so2_max 11 | , MIN(po2) AS po2_min, MAX(po2) AS po2_max 12 | , MIN(pco2) AS pco2_min, MAX(pco2) AS pco2_max 13 | , MIN(aado2) AS aado2_min, MAX(aado2) AS aado2_max 14 | , MIN(aado2_calc) AS aado2_calc_min, MAX(aado2_calc) AS aado2_calc_max 15 | , MIN(pao2fio2ratio) AS pao2fio2ratio_min, MAX(pao2fio2ratio) AS pao2fio2ratio_max 16 | , MIN(baseexcess) AS baseexcess_min, MAX(baseexcess) AS baseexcess_max 17 | , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max 18 | , MIN(totalco2) AS totalco2_min, MAX(totalco2) AS totalco2_max 19 | , MIN(hematocrit) AS hematocrit_min, MAX(hematocrit) AS hematocrit_max 20 | , MIN(hemoglobin) AS hemoglobin_min, MAX(hemoglobin) AS hemoglobin_max 21 | , MIN(carboxyhemoglobin) AS carboxyhemoglobin_min, MAX(carboxyhemoglobin) AS carboxyhemoglobin_max 22 | , MIN(methemoglobin) AS methemoglobin_min, MAX(methemoglobin) AS methemoglobin_max 23 | , MIN(temperature) AS temperature_min, MAX(temperature) AS temperature_max 24 | , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max 25 | , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max 26 | , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max 27 | , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max 28 | , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max 29 | FROM mimic_icu.icustays ie 30 | LEFT JOIN mimiciv.bg_mv bg 31 | ON ie.subject_id = bg.subject_id 32 | AND bg.specimen_pred = 'ART.' 33 | AND bg.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 34 | AND bg.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 35 | GROUP BY ie.subject_id, ie.stay_id 36 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/kdigo_creatinine_MV.sql: -------------------------------------------------------------------------------- 1 | -- Extract all creatinine values from labevents around patient's ICU stay 2 | 3 | CREATE MATERIALIZED VIEW mimiciv.kdigo_creatinine_mv AS 4 | 5 | WITH cr AS 6 | ( 7 | SELECT 8 | ie.hadm_id 9 | , ie.stay_id 10 | , le.charttime 11 | , AVG(le.valuenum) AS creat 12 | FROM mimic_icu.icustays ie 13 | LEFT JOIN mimic_hosp.labevents le 14 | ON ie.subject_id = le.subject_id 15 | AND le.ITEMID = 50912 16 | AND le.VALUENUM IS NOT NULL 17 | AND le.VALUENUM <= 150 18 | AND le.CHARTTIME BETWEEN DATE(ie.intime - INTERVAL '7 DAYS') AND ie.outtime 19 | GROUP BY ie.hadm_id, ie.stay_id, le.charttime 20 | ) 21 | , cr48 AS 22 | ( 23 | -- add in the lowest value in the previous 48 hours 24 | SELECT 25 | cr.stay_id 26 | , cr.charttime 27 | , MIN(cr48.creat) AS creat_low_past_48hr 28 | FROM cr 29 | -- add in all creatinine values in the last 48 hours 30 | LEFT JOIN cr cr48 31 | ON cr.stay_id = cr48.stay_id 32 | AND cr48.charttime < cr.charttime 33 | AND cr48.charttime >= DATE(cr.charttime - INTERVAL '48 HOUR') 34 | GROUP BY cr.stay_id, cr.charttime 35 | ) 36 | , cr7 AS 37 | ( 38 | -- add in the lowest value in the previous 7 days 39 | SELECT 40 | cr.stay_id 41 | , cr.charttime 42 | , MIN(cr7.creat) AS creat_low_past_7day 43 | FROM cr 44 | -- add in all creatinine values in the last 7 days 45 | LEFT JOIN cr cr7 46 | ON cr.stay_id = cr7.stay_id 47 | AND cr7.charttime < cr.charttime 48 | AND cr7.charttime >= DATE(cr.charttime - INTERVAL '7 DAY') 49 | GROUP BY cr.stay_id, cr.charttime 50 | ) 51 | SELECT 52 | cr.hadm_id 53 | , cr.stay_id 54 | , cr.charttime 55 | , cr.creat 56 | , cr48.creat_low_past_48hr 57 | , cr7.creat_low_past_7day 58 | FROM cr 59 | LEFT JOIN cr48 60 | ON cr.stay_id = cr48.stay_id 61 | AND cr.charttime = cr48.charttime 62 | LEFT JOIN cr7 63 | ON cr.stay_id = cr7.stay_id 64 | AND cr.charttime = cr7.charttime 65 | ; 66 | -------------------------------------------------------------------------------- /concepts_PG_local/demographics/icu_stay_hourly_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query generates a row for every hour the patient is in the ICU. 2 | -- The hours are based on clock-hours (i.e. 02:00, 03:00). 3 | -- The hour clock starts 24 hours before the first heart rate measurement. 4 | -- Note that the time of the first heart rate measurement is ceilinged to the hour. 5 | 6 | -- this query extracts the cohort and every possible hour they were in the ICU 7 | -- this table can be to other tables on ICUSTAY_ID and (ENDTIME - 1 hour,ENDTIME] 8 | 9 | -- get first/last measurement time 10 | 11 | with all_hours as 12 | ( 13 | select 14 | it.stay_id 15 | 16 | -- ceiling the intime to the nearest hour by adding 59 minutes then truncating 17 | -- note thart we truncate by parsing as string, rather than using DATETIME_TRUNC 18 | -- this is done to enable compatibility with psql 19 | -- , PARSE_DATETIME( 20 | -- '%Y-%m-%d %H:00:00', 21 | -- FORMAT_DATETIME( 22 | -- '%Y-%m-%d %H:00:00', 23 | , DATE_TRUNC('hour',it.intime_hr + INTERVAL '59 MINUTES') 24 | AS endtime 25 | -- , it.intime_hr AS intt -- can add to check 26 | -- , it.outtime_hr AS outt -- can add to check 27 | -- create integers for each charttime in hours from admission 28 | -- so 0 is admission time, 1 is one hour after admission, etc, up to ICU disch 29 | -- we allow 24 hours before ICU admission (to grab labs before admit) 30 | -- , generate_series(-24, (round(cast(extract(epoch from (it.outtime_hr - it.intime_hr)/3600 ) as numeric),0))) AS hrs 31 | , generate_series(-24, (ceil(cast(extract(epoch from (it.outtime_hr - it.intime_hr)/3600 ) as numeric)))) AS hrs 32 | -- , GENERATE_ARRAY(-24, CEIL(DATETIME_DIFF(it.outtime_hr, it.intime_hr, HOUR))) as hrs 33 | 34 | from mimiciv.icustay_times_mv it 35 | ) 36 | SELECT stay_id 37 | , CAST(hrs AS integer) as hr 38 | , (CAST(DATE_PART('hour', endtime) AS integer) + (CAST(hrs AS integer))) as endtime 39 | -- , intt -- can add to check 40 | -- , outt -- can add to check 41 | FROM all_hours 42 | 43 | -- CROSS JOIN UNNEST(all_hours.hrs) AS hr; - I don't know what this achieves 44 | -- CROSS JOIN UNNEST(array[all_hours.hrs]) AS hr2; -- this works, but no extra output 45 | -- cant get this last line to work. Series not an array. Nothing to unnest. 46 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/creatinine_baseline_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts the serum creatinine baselines of adult patients on each hospital admission. 2 | -- The baseline is determined by the following rules: 3 | -- i. if the lowest creatinine value during this admission is normal (<1.1), then use the value 4 | -- ii. if the patient is diagnosed with chronic kidney disease (CKD), then use the lowest creatinine value during the admission, although it may be rather large. 5 | -- iii. Otherwise, we estimate the baseline using the Simplified MDRD Formula: 6 | -- eGFR = 186 × Scr^(-1.154) × Age^(-0.203) × 0.742Female 7 | -- Let eGFR = 75. Scr = [ 75 / 186 / Age^(-0.203) / (0.742Female) ] ^ (1/-1.154) 8 | WITH p as 9 | ( 10 | SELECT 11 | ag.subject_id 12 | , ag.hadm_id 13 | , ag.age 14 | , p.gender 15 | , CASE WHEN p.gender='F' THEN 16 | POWER(75.0 / 186.0 / POWER(ag.age, -0.203) / 0.742, -1/1.154) 17 | ELSE 18 | POWER(75.0 / 186.0 / POWER(ag.age, -0.203), -1/1.154) 19 | END 20 | AS MDRD_est 21 | FROM mimiciv.age_mv ag 22 | LEFT JOIN mimic_core.patients p 23 | ON ag.subject_id = p.subject_id 24 | WHERE ag.age >= 18 25 | ) 26 | , lab as 27 | ( 28 | SELECT 29 | hadm_id 30 | , MIN(creatinine) AS scr_min 31 | FROM mimiciv.chemistry_mv 32 | GROUP BY hadm_id 33 | ) 34 | , ckd as 35 | ( 36 | SELECT hadm_id, MAX(1) AS CKD_flag 37 | FROM mimic_hosp.diagnoses_icd 38 | WHERE 39 | ( 40 | SUBSTR(icd_code, 1, 3) = '585' 41 | AND 42 | icd_version = 9 43 | ) 44 | OR 45 | ( 46 | SUBSTR(icd_code, 1, 3) = 'N18' 47 | AND 48 | icd_version = 10 49 | ) 50 | GROUP BY 1 51 | ) 52 | SELECT 53 | p.hadm_id 54 | , p.gender 55 | , p.age 56 | , lab.scr_min 57 | , COALESCE(ckd.ckd_flag, 0) AS ckd 58 | , p.MDRD_est 59 | , CASE 60 | WHEN lab.scr_min<=1.1 THEN scr_min 61 | WHEN ckd.ckd_flag=1 THEN scr_min 62 | ELSE MDRD_est END AS scr_baseline 63 | FROM p 64 | LEFT JOIN lab 65 | ON p.hadm_id = lab.hadm_id 66 | LEFT JOIN ckd 67 | ON p.hadm_id = ckd.hadm_id 68 | ; 69 | 70 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/chemistry_pg.sql: -------------------------------------------------------------------------------- 1 | -- extract chemistry labs 2 | -- excludes point of care tests (very rare) 3 | -- blood gas measurements are *not* included in this query 4 | -- instead they are in bg.sql 5 | SELECT 6 | MAX(subject_id) AS subject_id 7 | , MAX(hadm_id) AS hadm_id 8 | , MAX(charttime) AS charttime 9 | , le.specimen_id 10 | -- convert from itemid into a meaningful column 11 | , MAX(CASE WHEN itemid = 50862 AND valuenum <= 10 THEN valuenum ELSE NULL END) AS albumin 12 | , MAX(CASE WHEN itemid = 50930 AND valuenum <= 10 THEN valuenum ELSE NULL END) AS globulin 13 | , MAX(CASE WHEN itemid = 50976 AND valuenum <= 20 THEN valuenum ELSE NULL END) AS total_protein 14 | , MAX(CASE WHEN itemid = 50868 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS aniongap 15 | , MAX(CASE WHEN itemid = 50882 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS bicarbonate 16 | , MAX(CASE WHEN itemid = 51006 AND valuenum <= 300 THEN valuenum ELSE NULL END) AS bun 17 | , MAX(CASE WHEN itemid = 50893 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS calcium 18 | , MAX(CASE WHEN itemid = 50902 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS chloride 19 | , MAX(CASE WHEN itemid = 50912 AND valuenum <= 150 THEN valuenum ELSE NULL END) AS creatinine 20 | , MAX(CASE WHEN itemid = 50931 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose 21 | , MAX(CASE WHEN itemid = 50983 AND valuenum <= 200 THEN valuenum ELSE NULL END) AS sodium 22 | , MAX(CASE WHEN itemid = 50971 AND valuenum <= 30 THEN valuenum ELSE NULL END) AS potassium 23 | FROM mimic_hosp.labevents le 24 | WHERE le.itemid IN 25 | ( 26 | -- comment is: LABEL | CATEGORY | FLUID | NUMBER OF ROWS IN LABEVENTS 27 | 50862, -- ALBUMIN | CHEMISTRY | BLOOD | 146697 28 | 50930, -- Globulin 29 | 50976, -- Total protein 30 | 50868, -- ANION GAP | CHEMISTRY | BLOOD | 769895 31 | -- 52456, -- Anion gap, point of care test 32 | 50882, -- BICARBONATE | CHEMISTRY | BLOOD | 780733 33 | 50893, -- Calcium 34 | 50912, -- CREATININE | CHEMISTRY | BLOOD | 797476 35 | -- 52502, Creatinine, point of care 36 | 50902, -- CHLORIDE | CHEMISTRY | BLOOD | 795568 37 | 50931, -- GLUCOSE | CHEMISTRY | BLOOD | 748981 38 | -- 52525, Glucose, point of care 39 | 50971, -- POTASSIUM | CHEMISTRY | BLOOD | 845825 40 | -- 52566, -- Potassium, point of care 41 | 50983, -- SODIUM | CHEMISTRY | BLOOD | 808489 42 | -- 52579, -- Sodium, point of care 43 | 51006 -- UREA NITROGEN | CHEMISTRY | BLOOD | 791925 44 | -- 52603, Urea, point of care 45 | ) 46 | AND valuenum IS NOT NULL 47 | -- lab values cannot be 0 and cannot be negative 48 | -- .. except anion gap. 49 | AND (valuenum > 0 OR itemid = 50868) 50 | GROUP BY le.specimen_id 51 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/chemistry_mv.sql: -------------------------------------------------------------------------------- 1 | -- extract chemistry labs 2 | -- excludes point of care tests (very rare) 3 | -- blood gas measurements are *not* included in this query 4 | -- instead they are in bg.sql 5 | 6 | CREATE MATERIALIZED VIEW mimiciv.chemistry_mv AS 7 | 8 | SELECT 9 | MAX(subject_id) AS subject_id 10 | , MAX(hadm_id) AS hadm_id 11 | , MAX(charttime) AS charttime 12 | , le.specimen_id 13 | -- convert from itemid into a meaningful column 14 | , MAX(CASE WHEN itemid = 50862 AND valuenum <= 10 THEN valuenum ELSE NULL END) AS albumin 15 | , MAX(CASE WHEN itemid = 50930 AND valuenum <= 10 THEN valuenum ELSE NULL END) AS globulin 16 | , MAX(CASE WHEN itemid = 50976 AND valuenum <= 20 THEN valuenum ELSE NULL END) AS total_protein 17 | , MAX(CASE WHEN itemid = 50868 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS aniongap 18 | , MAX(CASE WHEN itemid = 50882 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS bicarbonate 19 | , MAX(CASE WHEN itemid = 51006 AND valuenum <= 300 THEN valuenum ELSE NULL END) AS bun 20 | , MAX(CASE WHEN itemid = 50893 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS calcium 21 | , MAX(CASE WHEN itemid = 50902 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS chloride 22 | , MAX(CASE WHEN itemid = 50912 AND valuenum <= 150 THEN valuenum ELSE NULL END) AS creatinine 23 | , MAX(CASE WHEN itemid = 50931 AND valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose 24 | , MAX(CASE WHEN itemid = 50983 AND valuenum <= 200 THEN valuenum ELSE NULL END) AS sodium 25 | , MAX(CASE WHEN itemid = 50971 AND valuenum <= 30 THEN valuenum ELSE NULL END) AS potassium 26 | FROM mimic_hosp.labevents le 27 | WHERE le.itemid IN 28 | ( 29 | -- comment is: LABEL | CATEGORY | FLUID | NUMBER OF ROWS IN LABEVENTS 30 | 50862, -- ALBUMIN | CHEMISTRY | BLOOD | 146697 31 | 50930, -- Globulin 32 | 50976, -- Total protein 33 | 50868, -- ANION GAP | CHEMISTRY | BLOOD | 769895 34 | -- 52456, -- Anion gap, point of care test 35 | 50882, -- BICARBONATE | CHEMISTRY | BLOOD | 780733 36 | 50893, -- Calcium 37 | 50912, -- CREATININE | CHEMISTRY | BLOOD | 797476 38 | -- 52502, Creatinine, point of care 39 | 50902, -- CHLORIDE | CHEMISTRY | BLOOD | 795568 40 | 50931, -- GLUCOSE | CHEMISTRY | BLOOD | 748981 41 | -- 52525, Glucose, point of care 42 | 50971, -- POTASSIUM | CHEMISTRY | BLOOD | 845825 43 | -- 52566, -- Potassium, point of care 44 | 50983, -- SODIUM | CHEMISTRY | BLOOD | 808489 45 | -- 52579, -- Sodium, point of care 46 | 51006 -- UREA NITROGEN | CHEMISTRY | BLOOD | 791925 47 | -- 52603, Urea, point of care 48 | ) 49 | AND valuenum IS NOT NULL 50 | -- lab values cannot be 0 and cannot be negative 51 | -- .. except anion gap. 52 | AND (valuenum > 0 OR itemid = 50868) 53 | GROUP BY le.specimen_id 54 | ; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/vitalsign_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query pivots the vital signs for the entire patient stay. 2 | -- Vital signs include heart rate, blood pressure, respiration rate, and temperature 3 | select 4 | ce.subject_id 5 | , ce.stay_id 6 | , ce.charttime 7 | , AVG(case when itemid in (220045) and valuenum > 0 and valuenum < 300 then valuenum else null end) as heart_rate 8 | , AVG(case when itemid in (220179,220050) and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp 9 | , AVG(case when itemid in (220180,220051) and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp 10 | , AVG(case when itemid in (220052,220181,225312) and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp 11 | , AVG(case when itemid = 220179 and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp_ni 12 | , AVG(case when itemid = 220180 and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp_ni 13 | , AVG(case when itemid = 220181 and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp_ni 14 | , AVG(case when itemid in (220210,224690) and valuenum > 0 and valuenum < 70 then valuenum else null end) as resp_rate 15 | , ROUND(CAST( 16 | AVG(case when itemid in (223761) and valuenum > 70 and valuenum < 120 then (valuenum-32)/1.8 -- converted to degC in valuenum call 17 | when itemid in (223762) and valuenum > 10 and valuenum < 50 then valuenum else null end) 18 | AS NUMERIC), 2) as temperature 19 | , MAX(CASE WHEN itemid = 224642 THEN value ELSE NULL END) AS temperature_site 20 | , AVG(case when itemid in (220277) and valuenum > 0 and valuenum <= 100 then valuenum else null end) as spo2 21 | , AVG(case when itemid in (225664,220621,226537) and valuenum > 0 then valuenum else null end) as glucose 22 | FROM mimic_icu.chartevents ce 23 | where ce.stay_id IS NOT NULL 24 | and ce.itemid in 25 | ( 26 | 220045, -- Heart Rate 27 | 225309, -- ART BP Systolic 28 | 225310, -- ART BP Diastolic 29 | 225312, -- ART BP Mean 30 | 220050, -- Arterial Blood Pressure systolic 31 | 220051, -- Arterial Blood Pressure diastolic 32 | 220052, -- Arterial Blood Pressure mean 33 | 220179, -- Non Invasive Blood Pressure systolic 34 | 220180, -- Non Invasive Blood Pressure diastolic 35 | 220181, -- Non Invasive Blood Pressure mean 36 | 220210, -- Respiratory Rate 37 | 224690, -- Respiratory Rate (Total) 38 | 220277, -- SPO2, peripheral 39 | -- GLUCOSE, both lab and fingerstick 40 | 225664, -- Glucose finger stick 41 | 220621, -- Glucose (serum) 42 | 226537, -- Glucose (whole blood) 43 | -- TEMPERATURE 44 | 223762, -- "Temperature Celsius" 45 | 223761, -- "Temperature Fahrenheit" 46 | 224642 -- Temperature Site 47 | -- 226329 -- Blood Temperature CCO (C) 48 | ) 49 | group by ce.subject_id, ce.stay_id, ce.charttime 50 | ; 51 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/vitalsign_mv.sql: -------------------------------------------------------------------------------- 1 | -- This query pivots the vital signs for the entire patient stay. 2 | -- Vital signs include heart rate, blood pressure, respiration rate, and temperature 3 | CREATE materialized view mimiciv.vitalsign_mv AS 4 | 5 | select 6 | ce.subject_id 7 | , ce.stay_id 8 | , ce.charttime 9 | , AVG(case when itemid in (220045) and valuenum > 0 and valuenum < 300 then valuenum else null end) as heart_rate 10 | , AVG(case when itemid in (220179,220050) and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp 11 | , AVG(case when itemid in (220180,220051) and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp 12 | , AVG(case when itemid in (220052,220181,225312) and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp 13 | , AVG(case when itemid = 220179 and valuenum > 0 and valuenum < 400 then valuenum else null end) as sbp_ni 14 | , AVG(case when itemid = 220180 and valuenum > 0 and valuenum < 300 then valuenum else null end) as dbp_ni 15 | , AVG(case when itemid = 220181 and valuenum > 0 and valuenum < 300 then valuenum else null end) as mbp_ni 16 | , AVG(case when itemid in (220210,224690) and valuenum > 0 and valuenum < 70 then valuenum else null end) as resp_rate 17 | , ROUND(CAST( 18 | AVG(case when itemid in (223761) and valuenum > 70 and valuenum < 120 then (valuenum-32)/1.8 -- converted to degC in valuenum call 19 | when itemid in (223762) and valuenum > 10 and valuenum < 50 then valuenum else null end) 20 | AS NUMERIC), 2) as temperature 21 | , MAX(CASE WHEN itemid = 224642 THEN value ELSE NULL END) AS temperature_site 22 | , AVG(case when itemid in (220277) and valuenum > 0 and valuenum <= 100 then valuenum else null end) as spo2 23 | , AVG(case when itemid in (225664,220621,226537) and valuenum > 0 then valuenum else null end) as glucose 24 | FROM mimic_icu.chartevents ce 25 | where ce.stay_id IS NOT NULL 26 | and ce.itemid in 27 | ( 28 | 220045, -- Heart Rate 29 | 225309, -- ART BP Systolic 30 | 225310, -- ART BP Diastolic 31 | 225312, -- ART BP Mean 32 | 220050, -- Arterial Blood Pressure systolic 33 | 220051, -- Arterial Blood Pressure diastolic 34 | 220052, -- Arterial Blood Pressure mean 35 | 220179, -- Non Invasive Blood Pressure systolic 36 | 220180, -- Non Invasive Blood Pressure diastolic 37 | 220181, -- Non Invasive Blood Pressure mean 38 | 220210, -- Respiratory Rate 39 | 224690, -- Respiratory Rate (Total) 40 | 220277, -- SPO2, peripheral 41 | -- GLUCOSE, both lab and fingerstick 42 | 225664, -- Glucose finger stick 43 | 220621, -- Glucose (serum) 44 | 226537, -- Glucose (whole blood) 45 | -- TEMPERATURE 46 | 223762, -- "Temperature Celsius" 47 | 223761, -- "Temperature Fahrenheit" 48 | 224642 -- Temperature Site 49 | -- 226329 -- Blood Temperature CCO (C) 50 | ) 51 | group by ce.subject_id, ce.stay_id, ce.charttime 52 | ; 53 | -------------------------------------------------------------------------------- /concepts_PG_local/measurement/ventilator_setting_pg.sql: -------------------------------------------------------------------------------- 1 | with ce as 2 | ( 3 | SELECT 4 | ce.subject_id 5 | , ce.stay_id 6 | , ce.charttime 7 | , itemid 8 | -- TODO: clean 9 | , value 10 | , case 11 | -- begin fio2 cleaning 12 | when itemid = 223835 13 | then 14 | case 15 | when valuenum >= 0.20 and valuenum <= 1 16 | then valuenum * 100 17 | -- improperly input data - looks like O2 flow in litres 18 | when valuenum > 1 and valuenum < 20 19 | then null 20 | when valuenum >= 20 and valuenum <= 100 21 | then valuenum 22 | ELSE NULL END 23 | -- end of fio2 cleaning 24 | -- begin peep cleaning 25 | WHEN itemid in (220339, 224700) 26 | THEN 27 | CASE 28 | WHEN valuenum > 100 THEN NULL 29 | WHEN valuenum < 0 THEN NULL 30 | ELSE valuenum END 31 | -- end peep cleaning 32 | ELSE valuenum END AS valuenum 33 | , valueuom 34 | , storetime 35 | FROM mimic_icu.chartevents ce 36 | where ce.value IS NOT NULL 37 | AND ce.stay_id IS NOT NULL 38 | AND ce.itemid IN 39 | ( 40 | 224688 -- Respiratory Rate (Set) 41 | , 224689 -- Respiratory Rate (spontaneous) 42 | , 224690 -- Respiratory Rate (Total) 43 | , 224687 -- minute volume 44 | , 224685, 224684, 224686 -- tidal volume 45 | , 224696 -- PlateauPressure 46 | , 220339, 224700 -- PEEP 47 | , 223835 -- fio2 48 | , 223849 -- vent mode 49 | , 229314 -- vent mode (Hamilton) 50 | , 223848 -- vent type 51 | ) 52 | ) 53 | SELECT 54 | subject_id 55 | , MAX(stay_id) AS stay_id 56 | , charttime 57 | , MAX(CASE WHEN itemid = 224688 THEN valuenum ELSE NULL END) AS respiratory_rate_set 58 | , MAX(CASE WHEN itemid = 224690 THEN valuenum ELSE NULL END) AS respiratory_rate_total 59 | , MAX(CASE WHEN itemid = 224689 THEN valuenum ELSE NULL END) AS respiratory_rate_spontaneous 60 | , MAX(CASE WHEN itemid = 224687 THEN valuenum ELSE NULL END) AS minute_volume 61 | , MAX(CASE WHEN itemid = 224684 THEN valuenum ELSE NULL END) AS tidal_volume_set 62 | , MAX(CASE WHEN itemid = 224685 THEN valuenum ELSE NULL END) AS tidal_volume_observed 63 | , MAX(CASE WHEN itemid = 224686 THEN valuenum ELSE NULL END) AS tidal_volume_spontaneous 64 | , MAX(CASE WHEN itemid = 224696 THEN valuenum ELSE NULL END) AS plateau_pressure 65 | , MAX(CASE WHEN itemid in (220339, 224700) THEN valuenum ELSE NULL END) AS peep 66 | , MAX(CASE WHEN itemid = 223835 THEN valuenum ELSE NULL END) AS fio2 67 | , MAX(CASE WHEN itemid = 223849 THEN value ELSE NULL END) AS ventilator_mode 68 | , MAX(CASE WHEN itemid = 229314 THEN value ELSE NULL END) AS ventilator_mode_hamilton 69 | , MAX(CASE WHEN itemid = 223848 THEN value ELSE NULL END) AS ventilator_type 70 | FROM ce 71 | GROUP BY subject_id, charttime 72 | ; 73 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/ventilator_setting_MV.sql: -------------------------------------------------------------------------------- 1 | CREATE MATERIALIZED VIEW mimiciv.ventilator_setting_mv AS 2 | 3 | 4 | with ce as 5 | ( 6 | SELECT 7 | ce.subject_id 8 | , ce.stay_id 9 | , ce.charttime 10 | , itemid 11 | -- TODO: clean 12 | , value 13 | , case 14 | -- begin fio2 cleaning 15 | when itemid = 223835 16 | then 17 | case 18 | when valuenum >= 0.20 and valuenum <= 1 19 | then valuenum * 100 20 | -- improperly input data - looks like O2 flow in litres 21 | when valuenum > 1 and valuenum < 20 22 | then null 23 | when valuenum >= 20 and valuenum <= 100 24 | then valuenum 25 | ELSE NULL END 26 | -- end of fio2 cleaning 27 | -- begin peep cleaning 28 | WHEN itemid in (220339, 224700) 29 | THEN 30 | CASE 31 | WHEN valuenum > 100 THEN NULL 32 | WHEN valuenum < 0 THEN NULL 33 | ELSE valuenum END 34 | -- end peep cleaning 35 | ELSE valuenum END AS valuenum 36 | , valueuom 37 | , storetime 38 | FROM mimic_icu.chartevents ce 39 | where ce.value IS NOT NULL 40 | AND ce.stay_id IS NOT NULL 41 | AND ce.itemid IN 42 | ( 43 | 224688 -- Respiratory Rate (Set) 44 | , 224689 -- Respiratory Rate (spontaneous) 45 | , 224690 -- Respiratory Rate (Total) 46 | , 224687 -- minute volume 47 | , 224685, 224684, 224686 -- tidal volume 48 | , 224696 -- PlateauPressure 49 | , 220339, 224700 -- PEEP 50 | , 223835 -- fio2 51 | , 223849 -- vent mode 52 | , 229314 -- vent mode (Hamilton) 53 | , 223848 -- vent type 54 | ) 55 | ) 56 | SELECT 57 | subject_id 58 | , MAX(stay_id) AS stay_id 59 | , charttime 60 | , MAX(CASE WHEN itemid = 224688 THEN valuenum ELSE NULL END) AS respiratory_rate_set 61 | , MAX(CASE WHEN itemid = 224690 THEN valuenum ELSE NULL END) AS respiratory_rate_total 62 | , MAX(CASE WHEN itemid = 224689 THEN valuenum ELSE NULL END) AS respiratory_rate_spontaneous 63 | , MAX(CASE WHEN itemid = 224687 THEN valuenum ELSE NULL END) AS minute_volume 64 | , MAX(CASE WHEN itemid = 224684 THEN valuenum ELSE NULL END) AS tidal_volume_set 65 | , MAX(CASE WHEN itemid = 224685 THEN valuenum ELSE NULL END) AS tidal_volume_observed 66 | , MAX(CASE WHEN itemid = 224686 THEN valuenum ELSE NULL END) AS tidal_volume_spontaneous 67 | , MAX(CASE WHEN itemid = 224696 THEN valuenum ELSE NULL END) AS plateau_pressure 68 | , MAX(CASE WHEN itemid in (220339, 224700) THEN valuenum ELSE NULL END) AS peep 69 | , MAX(CASE WHEN itemid = 223835 THEN valuenum ELSE NULL END) AS fio2 70 | , MAX(CASE WHEN itemid = 223849 THEN value ELSE NULL END) AS ventilator_mode 71 | , MAX(CASE WHEN itemid = 229314 THEN value ELSE NULL END) AS ventilator_mode_hamilton 72 | , MAX(CASE WHEN itemid = 223848 THEN value ELSE NULL END) AS ventilator_type 73 | FROM ce 74 | GROUP BY subject_id, charttime 75 | ; 76 | -------------------------------------------------------------------------------- /concepts_PG_local/organfailure/kdigo_stages_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query checks if the patient had AKI according to KDIGO. 2 | -- AKI is calculated every time a creatinine or urine output measurement occurs. 3 | -- Baseline creatinine is defined as the lowest creatinine in the past 7 days. 4 | 5 | -- get creatinine stages 6 | with cr_stg AS 7 | ( 8 | SELECT 9 | cr.stay_id 10 | , cr.charttime 11 | , cr.creat_low_past_7day 12 | , cr.creat_low_past_48hr 13 | , cr.creat 14 | , case 15 | -- 3x baseline 16 | when cr.creat >= (cr.creat_low_past_7day*3.0) then 3 17 | -- *OR* cr >= 4.0 with associated increase 18 | when cr.creat >= 4 19 | -- For patients reaching Stage 3 by SCr >4.0 mg/dl 20 | -- require that the patient first achieve ... acute increase >= 0.3 within 48 hr 21 | -- *or* an increase of >= 1.5 times baseline 22 | and (cr.creat_low_past_48hr <= 3.7 OR cr.creat >= (1.5*cr.creat_low_past_7day)) 23 | then 3 24 | -- TODO: initiation of RRT 25 | when cr.creat >= (cr.creat_low_past_7day*2.0) then 2 26 | when cr.creat >= (cr.creat_low_past_48hr+0.3) then 1 27 | when cr.creat >= (cr.creat_low_past_7day*1.5) then 1 28 | else 0 end as aki_stage_creat 29 | FROM mimiciv.kdigo_creatinine_mv cr 30 | ) 31 | -- stages for UO / creat 32 | , uo_stg as 33 | ( 34 | select 35 | uo.stay_id 36 | , uo.charttime 37 | , uo.weight 38 | , uo.uo_rt_6hr 39 | , uo.uo_rt_12hr 40 | , uo.uo_rt_24hr 41 | -- AKI stages according to urine output 42 | , CASE 43 | WHEN uo.uo_rt_6hr IS NULL THEN NULL 44 | -- require patient to be in ICU for at least 6 hours to stage UO 45 | WHEN uo.charttime <= DATE(ie.intime + INTERVAL '6 HOUR') THEN 0 46 | -- require the UO rate to be calculated over half the period 47 | -- i.e. for uo rate over 24 hours, require documentation at least 12 hr apart 48 | WHEN uo.uo_tm_24hr >= 11 AND uo.uo_rt_24hr < 0.3 THEN 3 49 | WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr = 0 THEN 3 50 | WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr < 0.5 THEN 2 51 | WHEN uo.uo_tm_6hr >= 2 AND uo.uo_rt_6hr < 0.5 THEN 1 52 | ELSE 0 END AS aki_stage_uo 53 | from mimiciv.kdigo_uo_mv uo 54 | INNER JOIN mimic_icu.icustays ie 55 | ON uo.stay_id = ie.stay_id 56 | ) 57 | -- get all charttimes documented 58 | , tm_stg AS 59 | ( 60 | SELECT 61 | stay_id, charttime 62 | FROM cr_stg 63 | UNION DISTINCT 64 | SELECT 65 | stay_id, charttime 66 | FROM uo_stg 67 | ) 68 | select 69 | ie.subject_id 70 | , ie.hadm_id 71 | , ie.stay_id 72 | , tm.charttime 73 | , cr.creat_low_past_7day 74 | , cr.creat_low_past_48hr 75 | , cr.creat 76 | , cr.aki_stage_creat 77 | , uo.uo_rt_6hr 78 | , uo.uo_rt_12hr 79 | , uo.uo_rt_24hr 80 | , uo.aki_stage_uo 81 | -- Classify AKI using both creatinine/urine output criteria 82 | , GREATEST(cr.aki_stage_creat, uo.aki_stage_uo) AS aki_stage 83 | FROM mimic_icu.icustays ie 84 | -- get all possible charttimes as listed in tm_stg 85 | LEFT JOIN tm_stg tm 86 | ON ie.stay_id = tm.stay_id 87 | LEFT JOIN cr_stg cr 88 | ON ie.stay_id = cr.stay_id 89 | AND tm.charttime = cr.charttime 90 | LEFT JOIN uo_stg uo 91 | ON ie.stay_id = uo.stay_id 92 | AND tm.charttime = uo.charttime 93 | ; -------------------------------------------------------------------------------- /concepts_PG_local/organfailure/kdigo_uo_pg.sql: -------------------------------------------------------------------------------- 1 | with ur_stg as 2 | ( 3 | select io.stay_id, io.charttime 4 | -- we have joined each row to all rows preceding within 24 hours 5 | -- we can now sum these rows to get total UO over the last 24 hours 6 | -- we can use case statements to restrict it to only the last 6/12 hours 7 | -- therefore we have three sums: 8 | -- 1) over a 6 hour period 9 | -- 2) over a 12 hour period 10 | -- 3) over a 24 hour period 11 | -- note that we assume data charted at charttime corresponds to 1 hour of UO 12 | -- therefore we use '5' and '11' to restrict the period, rather than 6/12 13 | -- this assumption may overestimate UO rate when documentation is done less than hourly 14 | 15 | -- 6 hours 16 | , sum(case when iosum.charttime >= DATE(io.charttime - interval '5 hour') 17 | then iosum.urineoutput 18 | else null end) as UrineOutput_6hr 19 | -- 12 hours 20 | , sum(case when iosum.charttime >= DATE(io.charttime - interval '11 hour') 21 | then iosum.urineoutput 22 | else null end) as UrineOutput_12hr 23 | -- 24 hours 24 | , sum(iosum.urineoutput) as UrineOutput_24hr 25 | 26 | -- calculate the number of hours over which we've tabulated UO 27 | , ROUND(CAST( 28 | EXTRACT(EPOCH FROM io.charttime - 29 | -- below MIN() gets the earliest time that was used in the summation 30 | MIN(case when iosum.charttime >= DATE(io.charttime - interval '5 hour') 31 | then iosum.charttime 32 | else null end) 33 | )/3600 as NUMERIC ),4) 34 | AS uo_tm_6hr 35 | -- repeat extraction for 12 hours and 24 hours 36 | , ROUND(CAST( 37 | EXTRACT(EPOCH FROM io.charttime - 38 | -- below MIN() gets the earliest time that was used in the summation 39 | MIN(case when iosum.charttime >= DATE(io.charttime - interval '11 hour') 40 | then iosum.charttime 41 | else null end) 42 | )/3600 as NUMERIC ),4) 43 | AS uo_tm_12hr 44 | , ROUND(CAST( 45 | EXTRACT(EPOCH FROM io.charttime - MIN(iosum.charttime) 46 | -- DATETIME_DIFF(io.charttime, MIN(iosum.charttime), SECOND) 47 | )/3600 as NUMERIC ),4) AS uo_tm_24hr 48 | -- AS NUMERIC)/3600.0, 4) AS uo_tm_24hr 49 | from mimiciv.urine_output_mv io 50 | -- this join gives all UO measurements over the 24 hours preceding this row 51 | left join mimiciv.urine_output_mv iosum 52 | on io.stay_id = iosum.stay_id 53 | and iosum.charttime <= io.charttime 54 | and iosum.charttime >= DATE(io.charttime - interval '23 hour') 55 | group by io.stay_id, io.charttime 56 | ) 57 | select 58 | ur.stay_id 59 | , ur.charttime 60 | , wd.weight 61 | , ur.urineoutput_6hr 62 | , ur.urineoutput_12hr 63 | , ur.urineoutput_24hr 64 | -- calculate rates - adding 1 hour as we assume data charted at 10:00 corresponds to previous hour 65 | , ROUND(CAST((ur.UrineOutput_6hr/wd.weight/(uo_tm_6hr+1)) AS NUMERIC), 4) AS uo_rt_6hr 66 | , ROUND(CAST((ur.UrineOutput_12hr/wd.weight/(uo_tm_12hr+1)) AS NUMERIC), 4) AS uo_rt_12hr 67 | , ROUND(CAST((ur.UrineOutput_24hr/wd.weight/(uo_tm_24hr+1)) AS NUMERIC), 4) AS uo_rt_24hr 68 | -- number of hours between current UO time and earliest charted UO within the X hour window 69 | , uo_tm_6hr 70 | , uo_tm_12hr 71 | , uo_tm_24hr 72 | from ur_stg ur 73 | left join mimiciv.weight_durations_mv wd 74 | on ur.stay_id = wd.stay_id 75 | and ur.charttime >= wd.starttime 76 | and ur.charttime < wd.endtime 77 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/kdigo_uo_MV.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE MATERIALIZED VIEW mimiciv.kdigo_uo_mv AS 3 | 4 | with ur_stg as 5 | ( 6 | select io.stay_id, io.charttime 7 | -- we have joined each row to all rows preceding within 24 hours 8 | -- we can now sum these rows to get total UO over the last 24 hours 9 | -- we can use case statements to restrict it to only the last 6/12 hours 10 | -- therefore we have three sums: 11 | -- 1) over a 6 hour period 12 | -- 2) over a 12 hour period 13 | -- 3) over a 24 hour period 14 | -- note that we assume data charted at charttime corresponds to 1 hour of UO 15 | -- therefore we use '5' and '11' to restrict the period, rather than 6/12 16 | -- this assumption may overestimate UO rate when documentation is done less than hourly 17 | 18 | -- 6 hours 19 | , sum(case when iosum.charttime >= DATE(io.charttime - interval '5 hour') 20 | then iosum.urineoutput 21 | else null end) as UrineOutput_6hr 22 | -- 12 hours 23 | , sum(case when iosum.charttime >= DATE(io.charttime - interval '11 hour') 24 | then iosum.urineoutput 25 | else null end) as UrineOutput_12hr 26 | -- 24 hours 27 | , sum(iosum.urineoutput) as UrineOutput_24hr 28 | 29 | -- calculate the number of hours over which we've tabulated UO 30 | , ROUND(CAST( 31 | EXTRACT(EPOCH FROM io.charttime - 32 | -- below MIN() gets the earliest time that was used in the summation 33 | MIN(case when iosum.charttime >= DATE(io.charttime - interval '5 hour') 34 | then iosum.charttime 35 | else null end) 36 | )/3600 as NUMERIC ),4) 37 | AS uo_tm_6hr 38 | -- repeat extraction for 12 hours and 24 hours 39 | , ROUND(CAST( 40 | EXTRACT(EPOCH FROM io.charttime - 41 | -- below MIN() gets the earliest time that was used in the summation 42 | MIN(case when iosum.charttime >= DATE(io.charttime - interval '11 hour') 43 | then iosum.charttime 44 | else null end) 45 | )/3600 as NUMERIC ),4) 46 | AS uo_tm_12hr 47 | , ROUND(CAST( 48 | EXTRACT(EPOCH FROM io.charttime - MIN(iosum.charttime) 49 | -- DATETIME_DIFF(io.charttime, MIN(iosum.charttime), SECOND) 50 | )/3600 as NUMERIC ),4) AS uo_tm_24hr 51 | -- AS NUMERIC)/3600.0, 4) AS uo_tm_24hr 52 | from mimiciv.urine_output_mv io 53 | -- this join gives all UO measurements over the 24 hours preceding this row 54 | left join mimiciv.urine_output_mv iosum 55 | on io.stay_id = iosum.stay_id 56 | and iosum.charttime <= io.charttime 57 | and iosum.charttime >= DATE(io.charttime - interval '23 hour') 58 | group by io.stay_id, io.charttime 59 | ) 60 | select 61 | ur.stay_id 62 | , ur.charttime 63 | , wd.weight 64 | , ur.urineoutput_6hr 65 | , ur.urineoutput_12hr 66 | , ur.urineoutput_24hr 67 | -- calculate rates - adding 1 hour as we assume data charted at 10:00 corresponds to previous hour 68 | , ROUND(CAST((ur.UrineOutput_6hr/wd.weight/(uo_tm_6hr+1)) AS NUMERIC), 4) AS uo_rt_6hr 69 | , ROUND(CAST((ur.UrineOutput_12hr/wd.weight/(uo_tm_12hr+1)) AS NUMERIC), 4) AS uo_rt_12hr 70 | , ROUND(CAST((ur.UrineOutput_24hr/wd.weight/(uo_tm_24hr+1)) AS NUMERIC), 4) AS uo_rt_24hr 71 | -- number of hours between current UO time and earliest charted UO within the X hour window 72 | , uo_tm_6hr 73 | , uo_tm_12hr 74 | , uo_tm_24hr 75 | from ur_stg ur 76 | left join mimiciv.weight_durations_mv wd 77 | on ur.stay_id = wd.stay_id 78 | and ur.charttime >= wd.starttime 79 | and ur.charttime < wd.endtime 80 | ; -------------------------------------------------------------------------------- /concepts_PG_local/score/sirs_pg.sql: -------------------------------------------------------------------------------- 1 | -- ------------------------------------------------------------------ 2 | -- Title: Systemic inflammatory response syndrome (SIRS) criteria 3 | -- This query extracts the Systemic inflammatory response syndrome (SIRS) criteria 4 | -- The criteria quantify the level of inflammatory response of the body 5 | -- The score is calculated on the first day of each ICU patients' stay. 6 | -- ------------------------------------------------------------------ 7 | 8 | -- Reference for SIRS: 9 | -- American College of Chest Physicians/Society of Critical Care Medicine Consensus Conference: 10 | -- definitions for sepsis and organ failure and guidelines for the use of innovative therapies in sepsis" 11 | -- Crit. Care Med. 20 (6): 864–74. 1992. 12 | -- doi:10.1097/00003246-199206000-00025. PMID 1597042. 13 | 14 | -- Variables used in SIRS: 15 | -- Body temperature (min and max) 16 | -- Heart rate (max) 17 | -- Respiratory rate (max) 18 | -- PaCO2 (min) 19 | -- White blood cell count (min and max) 20 | -- the presence of greater than 10% immature neutrophils (band forms) 21 | 22 | -- Note: 23 | -- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate stay_ids. 24 | -- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients. 25 | 26 | -- Aggregate the components for the score 27 | with scorecomp as 28 | ( 29 | select ie.stay_id 30 | , v.temperature_min 31 | , v.temperature_max 32 | , v.heart_rate_max 33 | , v.resp_rate_max 34 | , bg.pco2_min AS paco2_min 35 | , l.wbc_min 36 | , l.wbc_max 37 | , l.bands_max 38 | FROM mimic_icu.icustays ie 39 | left join mimiciv.first_day_bg_art_mv bg 40 | on ie.stay_id = bg.stay_id 41 | left join mimiciv.first_day_vitalsign_mv v 42 | on ie.stay_id = v.stay_id 43 | left join mimiciv.first_day_lab_mv l 44 | on ie.stay_id = l.stay_id 45 | ) 46 | , scorecalc as 47 | ( 48 | -- Calculate the final score 49 | -- note that if the underlying data is missing, the component is null 50 | -- eventually these are treated as 0 (normal), but knowing when data is missing is useful for debugging 51 | select stay_id 52 | 53 | , case 54 | when temperature_min < 36.0 then 1 55 | when temperature_max > 38.0 then 1 56 | when temperature_min is null then null 57 | else 0 58 | end as temp_score 59 | 60 | 61 | , case 62 | when heart_rate_max > 90.0 then 1 63 | when heart_rate_max is null then null 64 | else 0 65 | end as heart_rate_score 66 | 67 | , case 68 | when resp_rate_max > 20.0 then 1 69 | when paco2_min < 32.0 then 1 70 | when coalesce(resp_rate_max, paco2_min) is null then null 71 | else 0 72 | end as resp_score 73 | 74 | , case 75 | when wbc_min < 4.0 then 1 76 | when wbc_max > 12.0 then 1 77 | when bands_max > 10 then 1-- > 10% immature neurophils (band forms) 78 | when coalesce(wbc_min, bands_max) is null then null 79 | else 0 80 | end as wbc_score 81 | 82 | from scorecomp 83 | ) 84 | select 85 | ie.subject_id, ie.hadm_id, ie.stay_id 86 | -- Combine all the scores to get SOFA 87 | -- Impute 0 if the score is missing 88 | , coalesce(temp_score,0) 89 | + coalesce(heart_rate_score,0) 90 | + coalesce(resp_score,0) 91 | + coalesce(wbc_score,0) 92 | as sirs 93 | , temp_score, heart_rate_score, resp_score, wbc_score 94 | FROM mimic_icu.icustays ie 95 | left join scorecalc s 96 | on ie.stay_id = s.stay_id 97 | ; 98 | -------------------------------------------------------------------------------- /concepts_PG_local/demographics/weight_durations_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts weights for adult ICU patients with start/stop times 2 | -- if an admission weight is given, then this is assigned from intime to outtime 3 | WITH wt_stg as 4 | ( 5 | SELECT 6 | c.stay_id 7 | , c.charttime 8 | , case when c.itemid = 226512 then 'admit' 9 | else 'daily' end as weight_type 10 | -- TODO: eliminate obvious outliers if there is a reasonable weight 11 | , c.valuenum as weight 12 | FROM mimic_icu.chartevents c 13 | WHERE c.valuenum IS NOT NULL 14 | AND c.itemid in 15 | ( 16 | 226512 -- Admit Wt 17 | , 224639 -- Daily Weight 18 | ) 19 | AND c.valuenum > 0 20 | ) 21 | -- assign ascending row number 22 | , wt_stg1 as 23 | ( 24 | select 25 | stay_id 26 | , charttime 27 | , weight_type 28 | , weight 29 | , ROW_NUMBER() OVER (partition by stay_id, weight_type order by charttime) as rn 30 | from wt_stg 31 | WHERE weight IS NOT NULL 32 | ) 33 | -- change charttime to intime for the first admission weight recorded 34 | , wt_stg2 AS 35 | ( 36 | SELECT 37 | wt_stg1.stay_id 38 | , ie.intime, ie.outtime 39 | , wt_stg1.weight_type 40 | , case when wt_stg1.weight_type = 'admit' and wt_stg1.rn = 1 41 | then DATE(ie.intime - INTERVAL '2 HOURS') 42 | else wt_stg1.charttime end as starttime 43 | , wt_stg1.weight 44 | from wt_stg1 45 | INNER JOIN mimic_icu.icustays ie 46 | on ie.stay_id = wt_stg1.stay_id 47 | ) 48 | , wt_stg3 as 49 | ( 50 | select 51 | stay_id 52 | , intime, outtime 53 | , starttime 54 | , coalesce( 55 | LEAD(starttime) OVER (PARTITION BY stay_id ORDER BY starttime), 56 | DATE(outtime + INTERVAL '2 HOURS') 57 | ) as endtime 58 | , weight 59 | , weight_type 60 | from wt_stg2 61 | ) 62 | -- this table is the start/stop times from admit/daily weight in charted data 63 | , wt1 as 64 | ( 65 | select 66 | stay_id 67 | , starttime 68 | , coalesce(endtime, 69 | LEAD(starttime) OVER (partition by stay_id order by starttime), 70 | -- impute ICU discharge as the end of the final weight measurement 71 | -- plus a 2 hour "fuzziness" window 72 | DATE(outtime + INTERVAL '2 HOURS') 73 | ) as endtime 74 | , weight 75 | , weight_type 76 | from wt_stg3 77 | ) 78 | -- if the intime for the patient is < the first charted daily weight 79 | -- then we will have a "gap" at the start of their stay 80 | -- to prevent this, we look for these gaps and backfill the first weight 81 | -- this adds (153255-149657)=3598 rows, meaning this fix helps for up to 3598 stay_id 82 | , wt_fix as 83 | ( 84 | select ie.stay_id 85 | -- we add a 2 hour "fuzziness" window 86 | , DATE(ie.intime - INTERVAL '2 HOURS') as starttime 87 | , wt.starttime as endtime 88 | , wt.weight 89 | , wt.weight_type 90 | from mimic_icu.icustays ie 91 | inner join 92 | -- the below subquery returns one row for each unique stay_id 93 | -- the row contains: the first starttime and the corresponding weight 94 | ( 95 | SELECT wt1.stay_id, wt1.starttime, wt1.weight 96 | , weight_type 97 | , ROW_NUMBER() OVER (PARTITION BY wt1.stay_id ORDER BY wt1.starttime) as rn 98 | FROM wt1 99 | ) wt 100 | ON ie.stay_id = wt.stay_id 101 | AND wt.rn = 1 102 | and ie.intime < wt.starttime 103 | ) 104 | -- add the backfill rows to the main weight table 105 | SELECT 106 | wt1.stay_id 107 | , wt1.starttime 108 | , wt1.endtime 109 | , wt1.weight 110 | , wt1.weight_type 111 | FROM wt1 112 | UNION ALL 113 | SELECT 114 | wt_fix.stay_id 115 | , wt_fix.starttime 116 | , wt_fix.endtime 117 | , wt_fix.weight 118 | , wt_fix.weight_type 119 | FROM wt_fix; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/weight_durations_mv.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts weights for adult ICU patients with start/stop times 2 | -- if an admission weight is given, then this is assigned from intime to outtime 3 | 4 | CREATE materialized view mimiciv.weight_durations_mv AS 5 | 6 | WITH wt_stg as 7 | ( 8 | SELECT 9 | c.stay_id 10 | , c.charttime 11 | , case when c.itemid = 226512 then 'admit' 12 | else 'daily' end as weight_type 13 | -- TODO: eliminate obvious outliers if there is a reasonable weight 14 | , c.valuenum as weight 15 | FROM mimic_icu.chartevents c 16 | WHERE c.valuenum IS NOT NULL 17 | AND c.itemid in 18 | ( 19 | 226512 -- Admit Wt 20 | , 224639 -- Daily Weight 21 | ) 22 | AND c.valuenum > 0 23 | ) 24 | -- assign ascending row number 25 | , wt_stg1 as 26 | ( 27 | select 28 | stay_id 29 | , charttime 30 | , weight_type 31 | , weight 32 | , ROW_NUMBER() OVER (partition by stay_id, weight_type order by charttime) as rn 33 | from wt_stg 34 | WHERE weight IS NOT NULL 35 | ) 36 | -- change charttime to intime for the first admission weight recorded 37 | , wt_stg2 AS 38 | ( 39 | SELECT 40 | wt_stg1.stay_id 41 | , ie.intime, ie.outtime 42 | , wt_stg1.weight_type 43 | , case when wt_stg1.weight_type = 'admit' and wt_stg1.rn = 1 44 | then DATE(ie.intime - INTERVAL '2 HOURS') 45 | else wt_stg1.charttime end as starttime 46 | , wt_stg1.weight 47 | from wt_stg1 48 | INNER JOIN mimic_icu.icustays ie 49 | on ie.stay_id = wt_stg1.stay_id 50 | ) 51 | , wt_stg3 as 52 | ( 53 | select 54 | stay_id 55 | , intime, outtime 56 | , starttime 57 | , coalesce( 58 | LEAD(starttime) OVER (PARTITION BY stay_id ORDER BY starttime), 59 | DATE(outtime + INTERVAL '2 HOURS') 60 | ) as endtime 61 | , weight 62 | , weight_type 63 | from wt_stg2 64 | ) 65 | -- this table is the start/stop times from admit/daily weight in charted data 66 | , wt1 as 67 | ( 68 | select 69 | stay_id 70 | , starttime 71 | , coalesce(endtime, 72 | LEAD(starttime) OVER (partition by stay_id order by starttime), 73 | -- impute ICU discharge as the end of the final weight measurement 74 | -- plus a 2 hour "fuzziness" window 75 | DATE(outtime + INTERVAL '2 HOURS') 76 | ) as endtime 77 | , weight 78 | , weight_type 79 | from wt_stg3 80 | ) 81 | -- if the intime for the patient is < the first charted daily weight 82 | -- then we will have a "gap" at the start of their stay 83 | -- to prevent this, we look for these gaps and backfill the first weight 84 | -- this adds (153255-149657)=3598 rows, meaning this fix helps for up to 3598 stay_id 85 | , wt_fix as 86 | ( 87 | select ie.stay_id 88 | -- we add a 2 hour "fuzziness" window 89 | , DATE(ie.intime - INTERVAL '2 HOURS') as starttime 90 | , wt.starttime as endtime 91 | , wt.weight 92 | , wt.weight_type 93 | from mimic_icu.icustays ie 94 | inner join 95 | -- the below subquery returns one row for each unique stay_id 96 | -- the row contains: the first starttime and the corresponding weight 97 | ( 98 | SELECT wt1.stay_id, wt1.starttime, wt1.weight 99 | , weight_type 100 | , ROW_NUMBER() OVER (PARTITION BY wt1.stay_id ORDER BY wt1.starttime) as rn 101 | FROM wt1 102 | ) wt 103 | ON ie.stay_id = wt.stay_id 104 | AND wt.rn = 1 105 | and ie.intime < wt.starttime 106 | ) 107 | -- add the backfill rows to the main weight table 108 | SELECT 109 | wt1.stay_id 110 | , wt1.starttime 111 | , wt1.endtime 112 | , wt1.weight 113 | , wt1.weight_type 114 | FROM wt1 115 | UNION ALL 116 | SELECT 117 | wt_fix.stay_id 118 | , wt_fix.starttime 119 | , wt_fix.endtime 120 | , wt_fix.weight 121 | , wt_fix.weight_type 122 | FROM wt_fix; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/oxygen_delivery_pg.sql: -------------------------------------------------------------------------------- 1 | with ce_stg1 as 2 | ( 3 | SELECT 4 | ce.subject_id 5 | , ce.stay_id 6 | , ce.charttime 7 | , CASE 8 | -- merge o2 flows into a single row 9 | WHEN itemid IN (223834, 227582, 224691) THEN 223834 10 | ELSE itemid END AS itemid 11 | , value 12 | , valuenum 13 | , valueuom 14 | , storetime 15 | FROM mimic_icu.chartevents ce 16 | WHERE ce.value IS NOT NULL 17 | AND ce.itemid IN 18 | ( 19 | 223834 -- o2 flow 20 | , 227582 -- bipap o2 flow 21 | , 224691 -- Flow Rate (L) 22 | -- additional o2 flow is its own column 23 | , 227287 -- additional o2 flow 24 | ) 25 | ) 26 | , ce_stg2 AS 27 | ( 28 | select 29 | ce.subject_id 30 | , ce.stay_id 31 | , ce.charttime 32 | , itemid 33 | , value 34 | , valuenum 35 | , valueuom 36 | -- retain only 1 row per charttime 37 | -- prioritizing the last documented value 38 | -- primarily used to subselect o2 flows 39 | , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY storetime DESC) as rn 40 | FROM ce_stg1 ce 41 | ) 42 | , o2 AS 43 | ( 44 | -- The below ITEMID can have multiple entires for charttime/storetime 45 | -- These are totally valid entries, and should be retained in derived tables. 46 | -- 224181 -- Small Volume Neb Drug #1 | Respiratory | Text | chartevents 47 | -- , 227570 -- Small Volume Neb Drug/Dose #1 | Respiratory | Text | chartevents 48 | -- , 224833 -- SBT Deferred | Respiratory | Text | chartevents 49 | -- , 224716 -- SBT Stopped | Respiratory | Text | chartevents 50 | -- , 224740 -- RSBI Deferred | Respiratory | Text | chartevents 51 | -- , 224829 -- Trach Tube Type | Respiratory | Text | chartevents 52 | -- , 226732 -- O2 Delivery Device(s) | Respiratory | Text | chartevents 53 | -- , 226873 -- Inspiratory Ratio | Respiratory | Numeric | chartevents 54 | -- , 226871 -- Expiratory Ratio | Respiratory | Numeric | chartevents 55 | -- maximum of 4 o2 devices on at once 56 | SELECT 57 | subject_id 58 | , stay_id 59 | , charttime 60 | , itemid 61 | , value AS o2_device 62 | , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY value) as rn 63 | FROM mimic_icu.chartevents 64 | WHERE itemid = 226732 -- oxygen delivery device(s) 65 | ) 66 | , stg AS 67 | ( 68 | select 69 | COALESCE(ce.subject_id, o2.subject_id) AS subject_id 70 | , COALESCE(ce.stay_id, o2.stay_id) AS stay_id 71 | , COALESCE(ce.charttime, o2.charttime) AS charttime 72 | , COALESCE(ce.itemid, o2.itemid) AS itemid 73 | , ce.value 74 | , ce.valuenum 75 | , o2.o2_device 76 | , o2.rn 77 | from ce_stg2 ce 78 | FULL OUTER JOIN o2 79 | ON ce.subject_id = o2.subject_id 80 | AND ce.charttime = o2.charttime 81 | -- limit to 1 row per subject_id/charttime/itemid from ce_stg2 82 | WHERE ce.rn = 1 83 | ) 84 | SELECT 85 | subject_id 86 | , MAX(stay_id) AS stay_id 87 | , charttime 88 | , MAX(CASE WHEN itemid = 223834 THEN valuenum ELSE NULL END) AS o2_flow 89 | , MAX(CASE WHEN itemid = 227287 THEN valuenum ELSE NULL END) AS o2_flow_additional 90 | -- ensure we retain all o2 devices for the patient 91 | , MAX(CASE WHEN rn = 1 THEN o2_device ELSE NULL END) AS o2_delivery_device_1 92 | , MAX(CASE WHEN rn = 2 THEN o2_device ELSE NULL END) AS o2_delivery_device_2 93 | , MAX(CASE WHEN rn = 3 THEN o2_device ELSE NULL END) AS o2_delivery_device_3 94 | , MAX(CASE WHEN rn = 4 THEN o2_device ELSE NULL END) AS o2_delivery_device_4 95 | FROM stg 96 | GROUP BY subject_id, charttime 97 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/oxygen_delivery_MV.sql: -------------------------------------------------------------------------------- 1 | CREATE MATERIALIZED VIEW mimiciv.oxygen_delivery_mv AS 2 | 3 | 4 | with ce_stg1 as 5 | ( 6 | SELECT 7 | ce.subject_id 8 | , ce.stay_id 9 | , ce.charttime 10 | , CASE 11 | -- merge o2 flows into a single row 12 | WHEN itemid IN (223834, 227582, 224691) THEN 223834 13 | ELSE itemid END AS itemid 14 | , value 15 | , valuenum 16 | , valueuom 17 | , storetime 18 | FROM mimic_icu.chartevents ce 19 | WHERE ce.value IS NOT NULL 20 | AND ce.itemid IN 21 | ( 22 | 223834 -- o2 flow 23 | , 227582 -- bipap o2 flow 24 | , 224691 -- Flow Rate (L) 25 | -- additional o2 flow is its own column 26 | , 227287 -- additional o2 flow 27 | ) 28 | ) 29 | , ce_stg2 AS 30 | ( 31 | select 32 | ce.subject_id 33 | , ce.stay_id 34 | , ce.charttime 35 | , itemid 36 | , value 37 | , valuenum 38 | , valueuom 39 | -- retain only 1 row per charttime 40 | -- prioritizing the last documented value 41 | -- primarily used to subselect o2 flows 42 | , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY storetime DESC) as rn 43 | FROM ce_stg1 ce 44 | ) 45 | , o2 AS 46 | ( 47 | -- The below ITEMID can have multiple entires for charttime/storetime 48 | -- These are totally valid entries, and should be retained in derived tables. 49 | -- 224181 -- Small Volume Neb Drug #1 | Respiratory | Text | chartevents 50 | -- , 227570 -- Small Volume Neb Drug/Dose #1 | Respiratory | Text | chartevents 51 | -- , 224833 -- SBT Deferred | Respiratory | Text | chartevents 52 | -- , 224716 -- SBT Stopped | Respiratory | Text | chartevents 53 | -- , 224740 -- RSBI Deferred | Respiratory | Text | chartevents 54 | -- , 224829 -- Trach Tube Type | Respiratory | Text | chartevents 55 | -- , 226732 -- O2 Delivery Device(s) | Respiratory | Text | chartevents 56 | -- , 226873 -- Inspiratory Ratio | Respiratory | Numeric | chartevents 57 | -- , 226871 -- Expiratory Ratio | Respiratory | Numeric | chartevents 58 | -- maximum of 4 o2 devices on at once 59 | SELECT 60 | subject_id 61 | , stay_id 62 | , charttime 63 | , itemid 64 | , value AS o2_device 65 | , ROW_NUMBER() OVER (PARTITION BY subject_id, charttime, itemid ORDER BY value) as rn 66 | FROM mimic_icu.chartevents 67 | WHERE itemid = 226732 -- oxygen delivery device(s) 68 | ) 69 | , stg AS 70 | ( 71 | select 72 | COALESCE(ce.subject_id, o2.subject_id) AS subject_id 73 | , COALESCE(ce.stay_id, o2.stay_id) AS stay_id 74 | , COALESCE(ce.charttime, o2.charttime) AS charttime 75 | , COALESCE(ce.itemid, o2.itemid) AS itemid 76 | , ce.value 77 | , ce.valuenum 78 | , o2.o2_device 79 | , o2.rn 80 | from ce_stg2 ce 81 | FULL OUTER JOIN o2 82 | ON ce.subject_id = o2.subject_id 83 | AND ce.charttime = o2.charttime 84 | -- limit to 1 row per subject_id/charttime/itemid from ce_stg2 85 | WHERE ce.rn = 1 86 | ) 87 | SELECT 88 | subject_id 89 | , MAX(stay_id) AS stay_id 90 | , charttime 91 | , MAX(CASE WHEN itemid = 223834 THEN valuenum ELSE NULL END) AS o2_flow 92 | , MAX(CASE WHEN itemid = 227287 THEN valuenum ELSE NULL END) AS o2_flow_additional 93 | -- ensure we retain all o2 devices for the patient 94 | , MAX(CASE WHEN rn = 1 THEN o2_device ELSE NULL END) AS o2_delivery_device_1 95 | , MAX(CASE WHEN rn = 2 THEN o2_device ELSE NULL END) AS o2_delivery_device_2 96 | , MAX(CASE WHEN rn = 3 THEN o2_device ELSE NULL END) AS o2_delivery_device_3 97 | , MAX(CASE WHEN rn = 4 THEN o2_device ELSE NULL END) AS o2_delivery_device_4 98 | FROM stg 99 | GROUP BY subject_id, charttime 100 | ; -------------------------------------------------------------------------------- /concepts_PG_local/treatment/invasive_line_pg.sql: -------------------------------------------------------------------------------- 1 | 2 | -- metavision 3 | WITH mv AS 4 | ( 5 | SELECT 6 | stay_id 7 | -- since metavision separates lines using itemid, we can use it as the line number 8 | , mv.itemid AS line_number 9 | , di.label AS line_type 10 | , mv.location AS line_site 11 | , starttime, endtime 12 | FROM mimic_icu.procedureevents mv 13 | INNER JOIN mimic_icu.d_items di 14 | ON mv.itemid = di.itemid 15 | WHERE mv.itemid IN 16 | ( 17 | 227719 -- AVA Line 18 | , 225752 -- Arterial Line 19 | , 224269 -- CCO PAC 20 | , 224267 -- Cordis/Introducer 21 | , 224270 -- Dialysis Catheter 22 | , 224272 -- IABP line 23 | , 226124 -- ICP Catheter 24 | , 228169 -- Impella Line 25 | , 225202 -- Indwelling Port (PortaCath) 26 | , 228286 -- Intraosseous Device 27 | , 225204 -- Midline 28 | , 224263 -- Multi Lumen 29 | , 224560 -- PA Catheter 30 | , 224264 -- PICC Line 31 | , 225203 -- Pheresis Catheter 32 | , 224273 -- Presep Catheter 33 | , 225789 -- Sheath 34 | , 225761 -- Sheath Insertion 35 | , 228201 -- Tandem Heart Access Line 36 | , 228202 -- Tandem Heart Return Line 37 | , 224268 -- Trauma line 38 | , 225199 -- Triple Introducer 39 | , 225315 -- Tunneled (Hickman) Line 40 | , 225205 -- RIC 41 | ) 42 | ) 43 | -- as a final step, combine any similar terms together 44 | select 45 | stay_id 46 | , CASE 47 | WHEN line_type IN ('Arterial Line', 'A-Line') THEN 'Arterial' 48 | WHEN line_type IN ('CCO PA Line', 'CCO PAC') THEN 'Continuous Cardiac Output PA' 49 | WHEN line_type IN ('Dialysis Catheter', 'Dialysis Line') THEN 'Dialysis' 50 | WHEN line_type IN ('Hickman', 'Tunneled (Hickman) Line') THEN 'Hickman' 51 | WHEN line_type IN ('IABP', 'IABP line') THEN 'IABP' 52 | WHEN line_type IN ('Multi Lumen', 'Multi-lumen') THEN 'Multi Lumen' 53 | WHEN line_type IN ('PA Catheter', 'PA line') THEN 'PA' 54 | WHEN line_type IN ('PICC Line', 'PICC line') THEN 'PICC' 55 | WHEN line_type IN ('Pre-Sep Catheter', 'Presep Catheter') THEN 'Pre-Sep' 56 | WHEN line_type IN ('Trauma Line', 'Trauma line') THEN 'Trauma' 57 | WHEN line_type IN ('Triple Introducer', 'TripleIntroducer') THEN 'Triple Introducer' 58 | WHEN line_type IN ('Portacath', 'Indwelling Port (PortaCath)') THEN 'Portacath' 59 | -- the following lines were not merged with another line: 60 | -- AVA Line 61 | -- Camino Bolt 62 | -- Cordis/Introducer 63 | -- ICP Catheter 64 | -- Impella Line 65 | -- Intraosseous Device 66 | -- Introducer 67 | -- Lumbar Drain 68 | -- Midline 69 | -- Other/Remarks 70 | -- PacerIntroducer 71 | -- PermaCath 72 | -- Pheresis Catheter 73 | -- RIC 74 | -- Sheath 75 | -- Tandem Heart Access Line 76 | -- Tandem Heart Return Line 77 | -- Venous Access 78 | -- Ventriculostomy 79 | ELSE line_type END AS line_type 80 | , CASE 81 | WHEN line_site IN ('Left Antecub', 'Left Antecube') THEN 'Left Antecube' 82 | WHEN line_site IN ('Left Axilla', 'Left Axilla.') THEN 'Left Axilla' 83 | WHEN line_site IN ('Left Brachial', 'Left Brachial.') THEN 'Left Brachial' 84 | WHEN line_site IN ('Left Femoral', 'Left Femoral.') THEN 'Left Femoral' 85 | WHEN line_site IN ('Right Antecub', 'Right Antecube') THEN 'Right Antecube' 86 | WHEN line_site IN ('Right Axilla', 'Right Axilla.') THEN 'Right Axilla' 87 | WHEN line_site IN ('Right Brachial', 'Right Brachial.') THEN 'Right Brachial' 88 | WHEN line_site IN ('Right Femoral', 'Right Femoral.') THEN 'Right Femoral' 89 | -- the following sites were not merged with other sites: 90 | -- 'Left Foot' 91 | -- 'Left IJ' 92 | -- 'Left Radial' 93 | -- 'Left Subclavian' 94 | -- 'Left Ulnar' 95 | -- 'Left Upper Arm' 96 | -- 'Right Foot' 97 | -- 'Right IJ' 98 | -- 'Right Radial' 99 | -- 'Right Side Head' 100 | -- 'Right Subclavian' 101 | -- 'Right Ulnar' 102 | -- 'Right Upper Arm' 103 | -- 'Transthoracic' 104 | -- 'Other/Remarks' 105 | ELSE line_site END AS line_site 106 | , starttime 107 | , endtime 108 | FROM mv 109 | ORDER BY stay_id, starttime, line_type, line_site; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/urine_output_rate_pg.sql: -------------------------------------------------------------------------------- 1 | -- attempt to calculate urine output per hour 2 | -- rate/hour is the interpretable measure of kidney function 3 | -- though it is difficult to estimate from aperiodic point measures 4 | -- first we get the earliest heart rate documented for the stay 5 | WITH tm AS 6 | ( 7 | SELECT ie.stay_id 8 | , min(charttime) AS intime_hr 9 | , max(charttime) AS outtime_hr 10 | FROM mimic_icu.icustays ie 11 | INNER JOIN mimic_icu.chartevents ce 12 | ON ie.stay_id = ce.stay_id 13 | AND ce.itemid = 220045 14 | AND ce.charttime > DATE(ie.intime - INTERVAL '1 MONTH') 15 | AND ce.charttime < DATE(ie.outtime + INTERVAL '1 MONTH') 16 | GROUP BY ie.stay_id 17 | ) 18 | -- now calculate time since last UO measurement 19 | , uo_tm AS 20 | ( 21 | SELECT tm.stay_id 22 | , CASE 23 | WHEN LAG(charttime) OVER W IS NULL 24 | -- THEN DATETIME_DIFF(charttime, intime_hr, MINUTE) 25 | -- THEN DATE_PART('minute', intime_hr - charttime ) 26 | THEN EXTRACT(EPOCH FROM charttime -intime_hr )/60.0 27 | -- ELSE DATETIME_DIFF(charttime, LAG(charttime) OVER W, MINUTE) 28 | -- ELSE DATE_PART('minute', LAG(charttime) OVER W - charttime ) 29 | ELSE EXTRACT(EPOCH FROM charttime - LAG(charttime) OVER W )/60.0 30 | END AS tm_since_last_uo 31 | , uo.charttime 32 | , uo.urineoutput 33 | FROM tm 34 | INNER JOIN mimiciv.urine_output_mv uo 35 | ON tm.stay_id = uo.stay_id 36 | WINDOW W AS (PARTITION BY tm.stay_id ORDER BY charttime) 37 | ) 38 | , ur_stg as 39 | ( 40 | select io.stay_id, io.charttime 41 | -- we have joined each row to all rows preceding within 24 hours 42 | -- we can now sum these rows to get total UO over the last 24 hours 43 | -- we can use case statements to restrict it to only the last 6/12 hours 44 | -- therefore we have three sums: 45 | -- 1) over a 6 hour period 46 | -- 2) over a 12 hour period 47 | -- 3) over a 24 hour period 48 | , SUM(DISTINCT io.urineoutput) AS uo 49 | -- note that we assume data charted at charttime corresponds to 1 hour of UO 50 | -- therefore we use '5' and '11' to restrict the period, rather than 6/12 51 | -- this assumption may overestimate UO rate when documentation is done less than hourly 52 | 53 | -- , sum(case when DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 5 54 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 5 55 | then iosum.urineoutput 56 | else null end) as urineoutput_6hr 57 | --, SUM(CASE WHEN DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 5 58 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 5 59 | THEN iosum.tm_since_last_uo 60 | ELSE NULL END)/60.0 AS uo_tm_6hr 61 | -- , sum(case when DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 11 62 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 11 63 | then iosum.urineoutput 64 | else null end) as urineoutput_12hr 65 | -- , SUM(CASE WHEN DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 11 66 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 11 67 | THEN iosum.tm_since_last_uo 68 | ELSE NULL END)/60.0 AS uo_tm_12hr 69 | -- 24 hours 70 | , sum(iosum.urineoutput) as urineoutput_24hr 71 | , SUM(iosum.tm_since_last_uo)/60.0 AS uo_tm_24hr 72 | 73 | from uo_tm io 74 | -- this join gives you all UO measurements over a 24 hour period 75 | left join uo_tm iosum 76 | on io.stay_id = iosum.stay_id 77 | and io.charttime >= iosum.charttime 78 | and io.charttime <= (DATE(iosum.charttime + INTERVAL '23 HOUR')) 79 | group by io.stay_id, io.charttime 80 | ) 81 | select 82 | ur.stay_id 83 | , ur.charttime 84 | , wd.weight 85 | , ur.uo 86 | , ur.urineoutput_6hr 87 | , ur.urineoutput_12hr 88 | , ur.urineoutput_24hr 89 | , 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 90 | , 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 91 | , 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 92 | -- time of earliest UO measurement that was used to calculate the rate 93 | , ROUND(CAST((uo_tm_6hr) AS NUMERIC), 2) AS uo_tm_6hr 94 | , ROUND(CAST((uo_tm_12hr) AS NUMERIC), 2) AS uo_tm_12hr 95 | , ROUND(CAST((uo_tm_24hr) AS NUMERIC), 2) AS uo_tm_24hr 96 | from ur_stg ur 97 | LEFT JOIN mimiciv.weight_durations_mv wd 98 | ON ur.stay_id = wd.stay_id 99 | AND ur.charttime > wd.starttime 100 | AND ur.charttime <= wd.endtime 101 | AND wd.weight > 0 102 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/urine_output_rate_mv.sql: -------------------------------------------------------------------------------- 1 | -- attempt to calculate urine output per hour 2 | -- rate/hour is the interpretable measure of kidney function 3 | -- though it is difficult to estimate from aperiodic point measures 4 | -- first we get the earliest heart rate documented for the stay 5 | 6 | CREATE MATERIALIZED VIEW mimiciv.urine_output_rate_mv AS 7 | 8 | WITH tm AS 9 | ( 10 | SELECT ie.stay_id 11 | , min(charttime) AS intime_hr 12 | , max(charttime) AS outtime_hr 13 | FROM mimic_icu.icustays ie 14 | INNER JOIN mimic_icu.chartevents ce 15 | ON ie.stay_id = ce.stay_id 16 | AND ce.itemid = 220045 17 | AND ce.charttime > DATE(ie.intime - INTERVAL '1 MONTH') 18 | AND ce.charttime < DATE(ie.outtime + INTERVAL '1 MONTH') 19 | GROUP BY ie.stay_id 20 | ) 21 | -- now calculate time since last UO measurement 22 | , uo_tm AS 23 | ( 24 | SELECT tm.stay_id 25 | , CASE 26 | WHEN LAG(charttime) OVER W IS NULL 27 | -- THEN DATETIME_DIFF(charttime, intime_hr, MINUTE) 28 | -- THEN DATE_PART('minute', intime_hr - charttime ) 29 | THEN EXTRACT(EPOCH FROM charttime -intime_hr )/60.0 30 | -- ELSE DATETIME_DIFF(charttime, LAG(charttime) OVER W, MINUTE) 31 | -- ELSE DATE_PART('minute', LAG(charttime) OVER W - charttime ) 32 | ELSE EXTRACT(EPOCH FROM charttime - LAG(charttime) OVER W )/60.0 33 | END AS tm_since_last_uo 34 | , uo.charttime 35 | , uo.urineoutput 36 | FROM tm 37 | INNER JOIN mimiciv.urine_output_mv uo 38 | ON tm.stay_id = uo.stay_id 39 | WINDOW W AS (PARTITION BY tm.stay_id ORDER BY charttime) 40 | ) 41 | , ur_stg as 42 | ( 43 | select io.stay_id, io.charttime 44 | -- we have joined each row to all rows preceding within 24 hours 45 | -- we can now sum these rows to get total UO over the last 24 hours 46 | -- we can use case statements to restrict it to only the last 6/12 hours 47 | -- therefore we have three sums: 48 | -- 1) over a 6 hour period 49 | -- 2) over a 12 hour period 50 | -- 3) over a 24 hour period 51 | , SUM(DISTINCT io.urineoutput) AS uo 52 | -- note that we assume data charted at charttime corresponds to 1 hour of UO 53 | -- therefore we use '5' and '11' to restrict the period, rather than 6/12 54 | -- this assumption may overestimate UO rate when documentation is done less than hourly 55 | 56 | -- , sum(case when DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 5 57 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 5 58 | then iosum.urineoutput 59 | else null end) as urineoutput_6hr 60 | --, SUM(CASE WHEN DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 5 61 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 5 62 | THEN iosum.tm_since_last_uo 63 | ELSE NULL END)/60.0 AS uo_tm_6hr 64 | -- , sum(case when DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 11 65 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 11 66 | then iosum.urineoutput 67 | else null end) as urineoutput_12hr 68 | -- , SUM(CASE WHEN DATETIME_DIFF(io.charttime, iosum.charttime, HOUR) <= 11 69 | , sum(case when EXTRACT(EPOCH FROM io.charttime -iosum.charttime)/3600 <= 11 70 | THEN iosum.tm_since_last_uo 71 | ELSE NULL END)/60.0 AS uo_tm_12hr 72 | -- 24 hours 73 | , sum(iosum.urineoutput) as urineoutput_24hr 74 | , SUM(iosum.tm_since_last_uo)/60.0 AS uo_tm_24hr 75 | 76 | from uo_tm io 77 | -- this join gives you all UO measurements over a 24 hour period 78 | left join uo_tm iosum 79 | on io.stay_id = iosum.stay_id 80 | and io.charttime >= iosum.charttime 81 | and io.charttime <= (DATE(iosum.charttime + INTERVAL '23 HOUR')) 82 | group by io.stay_id, io.charttime 83 | ) 84 | select 85 | ur.stay_id 86 | , ur.charttime 87 | , wd.weight 88 | , ur.uo 89 | , ur.urineoutput_6hr 90 | , ur.urineoutput_12hr 91 | , ur.urineoutput_24hr 92 | , 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 93 | , 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 94 | , 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 95 | -- time of earliest UO measurement that was used to calculate the rate 96 | , ROUND(CAST((uo_tm_6hr) AS NUMERIC), 2) AS uo_tm_6hr 97 | , ROUND(CAST((uo_tm_12hr) AS NUMERIC), 2) AS uo_tm_12hr 98 | , ROUND(CAST((uo_tm_24hr) AS NUMERIC), 2) AS uo_tm_24hr 99 | from ur_stg ur 100 | LEFT JOIN mimiciv.weight_durations_mv wd 101 | ON ur.stay_id = wd.stay_id 102 | AND ur.charttime > wd.starttime 103 | AND ur.charttime <= wd.endtime 104 | AND wd.weight > 0 105 | ; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/gcs_pg.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts the Glasgow Coma Scale, a measure of neurological function. 2 | -- The query has a few special rules: 3 | -- (1) The verbal component can be set to 0 if the patient is ventilated. 4 | -- This is corrected to 5 - the overall GCS is set to 15 in these cases. 5 | -- (2) Often only one of three components is documented. The other components 6 | -- are carried forward. 7 | 8 | -- ITEMIDs used: 9 | 10 | -- METAVISION 11 | -- 223900 GCS - Verbal Response 12 | -- 223901 GCS - Motor Response 13 | -- 220739 GCS - Eye Opening 14 | 15 | -- Note: 16 | -- The GCS for sedated patients is defaulted to 15 in this code. 17 | -- This is in line with how the data is meant to be collected. 18 | -- e.g., from the SAPS II publication: 19 | -- For sedated patients, the Glasgow Coma Score before sedation was used. 20 | -- This was ascertained either from interviewing the physician who ordered the sedation, 21 | -- or by reviewing the patient's medical record. 22 | with base as 23 | ( 24 | select 25 | subject_id 26 | , ce.stay_id, ce.charttime 27 | -- pivot each value into its own column 28 | , max(case when ce.ITEMID = 223901 then ce.valuenum else null end) as GCSMotor 29 | , max(case 30 | when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 0 31 | when ce.ITEMID = 223900 then ce.valuenum 32 | else null 33 | end) as GCSVerbal 34 | , max(case when ce.ITEMID = 220739 then ce.valuenum else null end) as GCSEyes 35 | -- convert the data into a number, reserving a value of 0 for ET/Trach 36 | , max(case 37 | -- endotrach/vent is assigned a value of 0 38 | -- flag it here to later parse specially 39 | when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 1 -- metavision 40 | else 0 end) 41 | as endotrachflag 42 | , ROW_NUMBER () 43 | OVER (PARTITION BY ce.stay_id ORDER BY ce.charttime ASC) as rn 44 | from mimic_icu.chartevents ce 45 | -- Isolate the desired GCS variables 46 | where ce.ITEMID in 47 | ( 48 | -- GCS components, Metavision 49 | 223900, 223901, 220739 50 | ) 51 | group by ce.subject_id, ce.stay_id, ce.charttime 52 | ) 53 | , gcs as ( 54 | select b.* 55 | , b2.GCSVerbal as GCSVerbalPrev 56 | , b2.GCSMotor as GCSMotorPrev 57 | , b2.GCSEyes as GCSEyesPrev 58 | -- Calculate GCS, factoring in special case when they are intubated and prev vals 59 | -- note that the coalesce are used to implement the following if: 60 | -- if current value exists, use it 61 | -- if previous value exists, use it 62 | -- otherwise, default to normal 63 | , case 64 | -- replace GCS during sedation with 15 65 | when b.GCSVerbal = 0 66 | then 15 67 | when b.GCSVerbal is null and b2.GCSVerbal = 0 68 | then 15 69 | -- if previously they were intub, but they aren't now, do not use previous GCS values 70 | when b2.GCSVerbal = 0 71 | then 72 | coalesce(b.GCSMotor,6) 73 | + coalesce(b.GCSVerbal,5) 74 | + coalesce(b.GCSEyes,4) 75 | -- otherwise, add up score normally, imputing previous value if none available at current time 76 | else 77 | coalesce(b.GCSMotor,coalesce(b2.GCSMotor,6)) 78 | + coalesce(b.GCSVerbal,coalesce(b2.GCSVerbal,5)) 79 | + coalesce(b.GCSEyes,coalesce(b2.GCSEyes,4)) 80 | end as GCS 81 | 82 | from base b 83 | -- join to itself within 6 hours to get previous value 84 | left join base b2 85 | on b.stay_id = b2.stay_id 86 | and b.rn = b2.rn+1 87 | and b2.charttime > DATE(b.charttime - INTERVAL '6 HOURS') 88 | ) 89 | -- combine components with previous within 6 hours 90 | -- filter down to cohort which is not excluded 91 | -- truncate charttime to the hour 92 | , gcs_stg as 93 | ( 94 | select 95 | subject_id 96 | , gs.stay_id, gs.charttime 97 | , GCS 98 | , coalesce(GCSMotor,GCSMotorPrev) as GCSMotor 99 | , coalesce(GCSVerbal,GCSVerbalPrev) as GCSVerbal 100 | , coalesce(GCSEyes,GCSEyesPrev) as GCSEyes 101 | , case when coalesce(GCSMotor,GCSMotorPrev) is null then 0 else 1 end 102 | + case when coalesce(GCSVerbal,GCSVerbalPrev) is null then 0 else 1 end 103 | + case when coalesce(GCSEyes,GCSEyesPrev) is null then 0 else 1 end 104 | as components_measured 105 | , EndoTrachFlag 106 | from gcs gs 107 | ) 108 | -- priority is: 109 | -- (i) complete data, (ii) non-sedated GCS, (iii) lowest GCS, (iv) charttime 110 | , gcs_priority as 111 | ( 112 | select 113 | subject_id 114 | , stay_id 115 | , charttime 116 | , gcs 117 | , gcsmotor 118 | , gcsverbal 119 | , gcseyes 120 | , EndoTrachFlag 121 | , ROW_NUMBER() over 122 | ( 123 | PARTITION BY stay_id, charttime 124 | ORDER BY components_measured DESC, endotrachflag, gcs, charttime DESC 125 | ) as rn 126 | from gcs_stg 127 | ) 128 | select 129 | gs.subject_id 130 | , gs.stay_id 131 | , gs.charttime 132 | , GCS AS gcs 133 | , GCSMotor AS gcs_motor 134 | , GCSVerbal AS gcs_verbal 135 | , GCSEyes AS gcs_eyes 136 | , EndoTrachFlag AS gcs_unable 137 | from gcs_priority gs 138 | where rn = 1 139 | ; -------------------------------------------------------------------------------- /concepts_PG_local/treatment/crrt_pg.sql: -------------------------------------------------------------------------------- 1 | with crrt_settings as 2 | ( 3 | select ce.stay_id, ce.charttime 4 | , CASE WHEN ce.itemid = 227290 THEN ce.value END AS CRRT_mode 5 | , CASE WHEN ce.itemid = 224149 THEN ce.valuenum ELSE NULL END AS AccessPressure 6 | , CASE WHEN ce.itemid = 224144 THEN ce.valuenum ELSE NULL END AS BloodFlow -- (ml/min) 7 | , CASE WHEN ce.itemid = 228004 THEN ce.valuenum ELSE NULL END AS Citrate -- (ACD-A) 8 | , CASE WHEN ce.itemid = 225183 THEN ce.valuenum ELSE NULL END AS CurrentGoal 9 | , CASE WHEN ce.itemid = 225977 THEN ce.value ELSE NULL END AS DialysateFluid 10 | , CASE WHEN ce.itemid = 224154 THEN ce.valuenum ELSE NULL END AS DialysateRate 11 | , CASE WHEN ce.itemid = 224151 THEN ce.valuenum ELSE NULL END AS EffluentPressure 12 | , CASE WHEN ce.itemid = 224150 THEN ce.valuenum ELSE NULL END AS FilterPressure 13 | , CASE WHEN ce.itemid = 225958 THEN ce.value ELSE NULL END AS HeparinConcentration -- (units/mL) 14 | , CASE WHEN ce.itemid = 224145 THEN ce.valuenum ELSE NULL END AS HeparinDose -- (per hour) 15 | -- below may not account for drug infusion/hyperalimentation/anticoagulants infused 16 | , CASE WHEN ce.itemid = 224191 THEN ce.valuenum ELSE NULL END AS HourlyPatientFluidRemoval 17 | , CASE WHEN ce.itemid = 228005 THEN ce.valuenum ELSE NULL END AS PrefilterReplacementRate 18 | , CASE WHEN ce.itemid = 228006 THEN ce.valuenum ELSE NULL END AS PostFilterReplacementRate 19 | , CASE WHEN ce.itemid = 225976 THEN ce.value ELSE NULL END AS ReplacementFluid 20 | , CASE WHEN ce.itemid = 224153 THEN ce.valuenum ELSE NULL END AS ReplacementRate 21 | , CASE WHEN ce.itemid = 224152 THEN ce.valuenum ELSE NULL END AS ReturnPressure 22 | , CASE WHEN ce.itemid = 226457 THEN ce.valuenum END AS UltrafiltrateOutput 23 | -- separate system integrity into sub components 24 | -- need to do this as 224146 has multiple unique values for a single charttime 25 | -- e.g. "Clots Present" and "Active" at same time 26 | , CASE 27 | WHEN ce.itemid = 224146 28 | AND ce.value IN ('Active', 'Initiated', 'Reinitiated', 'New Filter') 29 | THEN 1 30 | WHEN ce.itemid = 224146 31 | AND ce.value IN ('Recirculating', 'Discontinued') 32 | THEN 0 33 | ELSE NULL END as system_active 34 | , CASE 35 | WHEN ce.itemid = 224146 36 | AND ce.value IN ('Clots Present', 'Clots Present') 37 | THEN 1 38 | WHEN ce.itemid = 224146 39 | AND ce.value IN ('No Clot Present', 'No Clot Present') 40 | THEN 0 41 | ELSE NULL END as clots 42 | , CASE 43 | WHEN ce.itemid = 224146 44 | AND ce.value IN ('Clots Increasing', 'Clot Increasing') 45 | THEN 1 46 | ELSE NULL END as clots_increasing 47 | , CASE 48 | WHEN ce.itemid = 224146 49 | AND ce.value IN ('Clotted') 50 | THEN 1 51 | ELSE NULL END as clotted 52 | from mimic_icu.chartevents ce 53 | where ce.itemid in 54 | ( 55 | -- MetaVision ITEMIDs 56 | 227290, -- CRRT Mode 57 | 224146, -- System Integrity 58 | -- 225956, -- Reason for CRRT Filter Change 59 | -- above itemid is one of: Clotted, Line Changed, Procedure 60 | -- only ~200 rows, not super useful 61 | 224149, -- Access Pressure 62 | 224144, -- Blood Flow (ml/min) 63 | 228004, -- Citrate (ACD-A) 64 | 225183, -- Current Goal 65 | 225977, -- Dialysate Fluid 66 | 224154, -- Dialysate Rate 67 | 224151, -- Effluent Pressure 68 | 224150, -- Filter Pressure 69 | 225958, -- Heparin Concentration (units/mL) 70 | 224145, -- Heparin Dose (per hour) 71 | 224191, -- Hourly Patient Fluid Removal 72 | 228005, -- PBP (Prefilter) Replacement Rate 73 | 228006, -- Post Filter Replacement Rate 74 | 225976, -- Replacement Fluid 75 | 224153, -- Replacement Rate 76 | 224152, -- Return Pressure 77 | 226457 -- Ultrafiltrate Output 78 | ) 79 | and ce.value is not null 80 | ) 81 | -- use MAX() to collapse to a single row 82 | -- there is only ever 1 row for unique combinations of stay_id/charttime/itemid 83 | select stay_id 84 | , charttime 85 | , MAX(crrt_mode) AS crrt_mode 86 | , MAX(AccessPressure) AS access_pressure 87 | , MAX(BloodFlow) AS blood_flow 88 | , MAX(Citrate) AS citrate 89 | , MAX(CurrentGoal) AS current_goal 90 | , MAX(DialysateFluid) AS dialysate_fluid 91 | , MAX(DialysateRate) AS dialysate_rate 92 | , MAX(EffluentPressure) AS effluent_pressure 93 | , MAX(FilterPressure) AS filter_pressure 94 | , MAX(HeparinConcentration) AS heparin_concentration 95 | , MAX(HeparinDose) AS heparin_dose 96 | , MAX(HourlyPatientFluidRemoval) AS hourly_patient_fluid_removal 97 | , MAX(PrefilterReplacementRate) AS prefilter_replacement_rate 98 | , MAX(PostFilterReplacementRate) AS postfilter_replacement_rate 99 | , MAX(ReplacementFluid) AS replacement_fluid 100 | , MAX(ReplacementRate) AS replacement_rate 101 | , MAX(ReturnPressure) AS return_pressure 102 | , MAX(UltrafiltrateOutput) AS ultrafiltrate_output 103 | , MAX(system_active) AS system_active 104 | , MAX(clots) AS clots 105 | , MAX(clots_increasing) AS clots_increasing 106 | , MAX(clotted) AS clotted 107 | from crrt_settings 108 | group by stay_id, charttime -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/gcs_mv.sql: -------------------------------------------------------------------------------- 1 | -- This query extracts the Glasgow Coma Scale, a measure of neurological function. 2 | -- The query has a few special rules: 3 | -- (1) The verbal component can be set to 0 if the patient is ventilated. 4 | -- This is corrected to 5 - the overall GCS is set to 15 in these cases. 5 | -- (2) Often only one of three components is documented. The other components 6 | -- are carried forward. 7 | 8 | -- ITEMIDs used: 9 | 10 | -- METAVISION 11 | -- 223900 GCS - Verbal Response 12 | -- 223901 GCS - Motor Response 13 | -- 220739 GCS - Eye Opening 14 | 15 | -- Note: 16 | -- The GCS for sedated patients is defaulted to 15 in this code. 17 | -- This is in line with how the data is meant to be collected. 18 | -- e.g., from the SAPS II publication: 19 | -- For sedated patients, the Glasgow Coma Score before sedation was used. 20 | -- This was ascertained either from interviewing the physician who ordered the sedation, 21 | -- or by reviewing the patient's medical record. 22 | 23 | CREATE MATERIALIZED VIEW mimiciv.gcs_mv AS 24 | 25 | with base as 26 | ( 27 | select 28 | subject_id 29 | , ce.stay_id, ce.charttime 30 | -- pivot each value into its own column 31 | , max(case when ce.ITEMID = 223901 then ce.valuenum else null end) as GCSMotor 32 | , max(case 33 | when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 0 34 | when ce.ITEMID = 223900 then ce.valuenum 35 | else null 36 | end) as GCSVerbal 37 | , max(case when ce.ITEMID = 220739 then ce.valuenum else null end) as GCSEyes 38 | -- convert the data into a number, reserving a value of 0 for ET/Trach 39 | , max(case 40 | -- endotrach/vent is assigned a value of 0 41 | -- flag it here to later parse specially 42 | when ce.ITEMID = 223900 and ce.VALUE = 'No Response-ETT' then 1 -- metavision 43 | else 0 end) 44 | as endotrachflag 45 | , ROW_NUMBER () 46 | OVER (PARTITION BY ce.stay_id ORDER BY ce.charttime ASC) as rn 47 | from mimic_icu.chartevents ce 48 | -- Isolate the desired GCS variables 49 | where ce.ITEMID in 50 | ( 51 | -- GCS components, Metavision 52 | 223900, 223901, 220739 53 | ) 54 | group by ce.subject_id, ce.stay_id, ce.charttime 55 | ) 56 | , gcs as ( 57 | select b.* 58 | , b2.GCSVerbal as GCSVerbalPrev 59 | , b2.GCSMotor as GCSMotorPrev 60 | , b2.GCSEyes as GCSEyesPrev 61 | -- Calculate GCS, factoring in special case when they are intubated and prev vals 62 | -- note that the coalesce are used to implement the following if: 63 | -- if current value exists, use it 64 | -- if previous value exists, use it 65 | -- otherwise, default to normal 66 | , case 67 | -- replace GCS during sedation with 15 68 | when b.GCSVerbal = 0 69 | then 15 70 | when b.GCSVerbal is null and b2.GCSVerbal = 0 71 | then 15 72 | -- if previously they were intub, but they aren't now, do not use previous GCS values 73 | when b2.GCSVerbal = 0 74 | then 75 | coalesce(b.GCSMotor,6) 76 | + coalesce(b.GCSVerbal,5) 77 | + coalesce(b.GCSEyes,4) 78 | -- otherwise, add up score normally, imputing previous value if none available at current time 79 | else 80 | coalesce(b.GCSMotor,coalesce(b2.GCSMotor,6)) 81 | + coalesce(b.GCSVerbal,coalesce(b2.GCSVerbal,5)) 82 | + coalesce(b.GCSEyes,coalesce(b2.GCSEyes,4)) 83 | end as GCS 84 | 85 | from base b 86 | -- join to itself within 6 hours to get previous value 87 | left join base b2 88 | on b.stay_id = b2.stay_id 89 | and b.rn = b2.rn+1 90 | and b2.charttime > DATE(b.charttime - INTERVAL '6 HOURS') 91 | ) 92 | -- combine components with previous within 6 hours 93 | -- filter down to cohort which is not excluded 94 | -- truncate charttime to the hour 95 | , gcs_stg as 96 | ( 97 | select 98 | subject_id 99 | , gs.stay_id, gs.charttime 100 | , GCS 101 | , coalesce(GCSMotor,GCSMotorPrev) as GCSMotor 102 | , coalesce(GCSVerbal,GCSVerbalPrev) as GCSVerbal 103 | , coalesce(GCSEyes,GCSEyesPrev) as GCSEyes 104 | , case when coalesce(GCSMotor,GCSMotorPrev) is null then 0 else 1 end 105 | + case when coalesce(GCSVerbal,GCSVerbalPrev) is null then 0 else 1 end 106 | + case when coalesce(GCSEyes,GCSEyesPrev) is null then 0 else 1 end 107 | as components_measured 108 | , EndoTrachFlag 109 | from gcs gs 110 | ) 111 | -- priority is: 112 | -- (i) complete data, (ii) non-sedated GCS, (iii) lowest GCS, (iv) charttime 113 | , gcs_priority as 114 | ( 115 | select 116 | subject_id 117 | , stay_id 118 | , charttime 119 | , gcs 120 | , gcsmotor 121 | , gcsverbal 122 | , gcseyes 123 | , EndoTrachFlag 124 | , ROW_NUMBER() over 125 | ( 126 | PARTITION BY stay_id, charttime 127 | ORDER BY components_measured DESC, endotrachflag, gcs, charttime DESC 128 | ) as rn 129 | from gcs_stg 130 | ) 131 | select 132 | gs.subject_id 133 | , gs.stay_id 134 | , gs.charttime 135 | , GCS AS gcs 136 | , GCSMotor AS gcs_motor 137 | , GCSVerbal AS gcs_verbal 138 | , GCSEyes AS gcs_eyes 139 | , EndoTrachFlag AS gcs_unable 140 | from gcs_priority gs 141 | where rn = 1 142 | ; -------------------------------------------------------------------------------- /concepts_PG_local/organfailure/meld_pg.sql: -------------------------------------------------------------------------------- 1 | -- Model for end-stage liver disease (MELD) 2 | -- This model is used to determine prognosis and receipt of liver transplantation. 3 | 4 | -- Reference: 5 | -- Kamath PS, Wiesner RH, Malinchoc M, Kremers W, Therneau TM, 6 | -- Kosberg CL, D'Amico G, Dickson ER, Kim WR. 7 | -- A model to predict survival in patients with end-stage liver disease. 8 | -- Hepatology. 2001 Feb;33(2):464-70. 9 | 10 | 11 | -- Updated January 2016 to include serum sodium, see: 12 | -- https://optn.transplant.hrsa.gov/news/meld-serum-sodium-policy-changes/ 13 | 14 | -- Here is the relevant portion of the policy note: 15 | -- 9.1.D MELD Score 16 | -- Candidates who are at least 12 years old receive an initial MELD(i) score equal to: 17 | -- 0.957 x ln(creatinine mg/dL) + 0.378 x ln(bilirubin mg/dL) + 1.120 x ln(INR) + 0.643 18 | 19 | -- Laboratory values less than 1.0 will be set to 1.0 when calculating a candidate’s MELD 20 | -- score. 21 | 22 | -- The following candidates will receive a creatinine value of 4.0 mg/dL: 23 | -- - Candidates with a creatinine value greater than 4.0 mg/dL 24 | -- - Candidates who received two or more dialysis treatments within the prior week 25 | -- - Candidates who received 24 hours of continuous veno-venous hemodialysis (CVVHD) within the prior week 26 | 27 | -- The maximum MELD score is 40. The MELD score derived from this calculation will be rounded to the tenth decimal place and then multiplied by 10. 28 | 29 | -- For candidates with an initial MELD score greater than 11, The MELD score is then recalculated as follows: 30 | -- MELD = MELD(i) + 1.32*(137-Na) – [0.033*MELD(i)*(137-Na)] 31 | -- Sodium values less than 125 mmol/L will be set to 125, and values greater than 137 mmol/L will be set to 137. 32 | 33 | 34 | 35 | -- TODO needed in this code: 36 | -- 1. identify 2x dialysis in the past week, or 24 hours of CVVH 37 | -- at the moment it just checks for any dialysis on the first day 38 | -- 2. identify cholestatic or alcoholic liver disease 39 | -- 0.957 x ln(creatinine mg/dL) + 0.378 x ln(bilirubin mg/dL) + 1.120 x ln(INR) + 0.643 x etiology 40 | -- (0 if cholestatic or alcoholic, 1 otherwise) 41 | -- 3. adjust the serum sodium using the corresponding glucose measurement 42 | -- Measured sodium + 0.024 * (Serum glucose - 100) (Hiller, 1999) 43 | WITH cohort AS 44 | ( 45 | SELECT 46 | ie.subject_id 47 | , ie.hadm_id 48 | , ie.stay_id 49 | , ie.intime 50 | , ie.outtime 51 | 52 | , labs.creatinine_max 53 | , labs.bilirubin_total_max 54 | , labs.inr_max 55 | , labs.sodium_min 56 | 57 | , r.dialysis_present AS rrt 58 | 59 | FROM mimic_icu.icustays ie 60 | -- join to custom tables to get more data.... 61 | LEFT JOIN mimiciv.first_day_lab_mv labs 62 | ON ie.stay_id = labs.stay_id 63 | LEFT JOIN mimiciv.first_day_rrt_mv r 64 | ON ie.stay_id = r.stay_id 65 | ) 66 | , score as 67 | ( 68 | SELECT 69 | subject_id 70 | , hadm_id 71 | , stay_id 72 | , rrt 73 | , creatinine_max 74 | , bilirubin_total_max 75 | , inr_max 76 | , sodium_min 77 | 78 | -- TODO: Corrected Sodium 79 | , CASE 80 | WHEN sodium_min is null 81 | THEN 0.0 82 | WHEN sodium_min > 137 83 | THEN 0.0 84 | WHEN sodium_min < 125 85 | THEN 12.0 -- 137 - 125 = 12 86 | else 137.0-sodium_min 87 | end as sodium_score 88 | 89 | -- if hemodialysis, value for Creatinine is automatically set to 4.0 90 | , CASE 91 | WHEN rrt = 1 or creatinine_max > 4.0 92 | THEN (0.957 * ln(4)) 93 | -- if creatinine < 1, score is 1 94 | WHEN creatinine_max < 1 95 | THEN (0.957 * ln(1)) 96 | else 0.957 * coalesce(ln(creatinine_max),ln(1)) 97 | end as creatinine_score 98 | 99 | , CASE 100 | -- if value < 1, score is 1 101 | WHEN bilirubin_total_max < 1 102 | THEN 0.378 * ln(1) 103 | else 0.378 * coalesce(ln(bilirubin_total_max),ln(1)) 104 | end as bilirubin_score 105 | 106 | , CASE 107 | WHEN inr_max < 1 108 | THEN ( 1.120 * ln(1) + 0.643 ) 109 | else ( 1.120 * coalesce(ln(inr_max),ln(1)) + 0.643 ) 110 | end as inr_score 111 | 112 | FROM cohort 113 | ) 114 | , score2 as 115 | ( 116 | SELECT 117 | subject_id 118 | , hadm_id 119 | , stay_id 120 | , rrt 121 | , creatinine_max 122 | , bilirubin_total_max 123 | , inr_max 124 | , sodium_min 125 | 126 | , creatinine_score 127 | , sodium_score 128 | , bilirubin_score 129 | , inr_score 130 | 131 | , CASE 132 | WHEN (creatinine_score + bilirubin_score + inr_score) > 4 133 | THEN 40.0 134 | else 135 | round(cast(creatinine_score + bilirubin_score + inr_score as numeric),1)*10 136 | end as meld_initial 137 | FROM score 138 | ) 139 | SELECT 140 | subject_id 141 | , hadm_id 142 | , stay_id 143 | 144 | -- MELD Score without sodium change 145 | , meld_initial 146 | 147 | -- MELD Score (2016) = MELD*10 + 1.32*(137-Na) – [0.033*MELD*10*(137-Na)] 148 | , CASE 149 | WHEN meld_initial > 11 150 | THEN meld_initial + 1.32*sodium_score - 0.033*meld_initial*sodium_score 151 | else 152 | meld_initial 153 | end as meld 154 | 155 | -- original variables 156 | , rrt 157 | , creatinine_max 158 | , bilirubin_total_max 159 | , inr_max 160 | , sodium_min 161 | 162 | FROM score2 163 | ; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/blood_differential_pg.sql: -------------------------------------------------------------------------------- 1 | -- For reference, some common unit conversions: 2 | -- 10^9/L == K/uL == 10^3/uL 3 | WITH blood_diff AS 4 | ( 5 | SELECT 6 | MAX(subject_id) AS subject_id 7 | , MAX(hadm_id) AS hadm_id 8 | , MAX(charttime) AS charttime 9 | , le.specimen_id 10 | -- create one set of columns for percentages, and one set of columns for counts 11 | -- we harmonize all count units into K/uL == 10^9/L 12 | -- counts have an "_abs" suffix, percentages do not 13 | 14 | -- absolute counts 15 | , MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) AS wbc 16 | , MAX(CASE WHEN itemid = 52069 THEN valuenum ELSE NULL END) AS basophils_abs 17 | -- 52073 in K/uL, 51199 in #/uL 18 | , MAX(CASE WHEN itemid = 52073 THEN valuenum WHEN itemid = 51199 THEN valuenum / 1000.0 ELSE NULL END) AS eosinophils_abs 19 | -- 51133 in K/uL, 52769 in #/uL 20 | , MAX(CASE WHEN itemid = 51133 THEN valuenum WHEN itemid = 52769 THEN valuenum / 1000.0 ELSE NULL END) AS lymphocytes_abs 21 | -- 52074 in K/uL, 51253 in #/uL 22 | , MAX(CASE WHEN itemid = 52074 THEN valuenum WHEN itemid = 51253 THEN valuenum / 1000.0 ELSE NULL END) AS monocytes_abs 23 | , MAX(CASE WHEN itemid = 52075 THEN valuenum ELSE NULL END) AS neutrophils_abs 24 | -- convert from #/uL to K/uL 25 | , MAX(CASE WHEN itemid = 51218 THEN valuenum / 1000.0 ELSE NULL END) AS granulocytes_abs 26 | 27 | -- percentages, equal to cell count / white blood cell count 28 | , MAX(CASE WHEN itemid = 51146 THEN valuenum ELSE NULL END) AS basophils 29 | , MAX(CASE WHEN itemid = 51200 THEN valuenum ELSE NULL END) AS eosinophils 30 | , MAX(CASE WHEN itemid in (51244, 51245) THEN valuenum ELSE NULL END) AS lymphocytes 31 | , MAX(CASE WHEN itemid = 51254 THEN valuenum ELSE NULL END) AS monocytes 32 | , MAX(CASE WHEN itemid = 51256 THEN valuenum ELSE NULL END) AS neutrophils 33 | 34 | -- other cell count percentages 35 | , MAX(CASE WHEN itemid = 51143 THEN valuenum ELSE NULL END) AS atypical_lymphocytes 36 | , MAX(CASE WHEN itemid = 51144 THEN valuenum ELSE NULL END) AS bands 37 | , MAX(CASE WHEN itemid = 52135 THEN valuenum ELSE NULL END) AS immature_granulocytes 38 | , MAX(CASE WHEN itemid = 51251 THEN valuenum ELSE NULL END) AS metamyelocytes 39 | , MAX(CASE WHEN itemid = 51257 THEN valuenum ELSE NULL END) AS nrbc 40 | 41 | -- utility flags which determine whether imputation is possible 42 | , CASE 43 | -- WBC is available 44 | WHEN MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) > 0 45 | -- and we have at least one percentage from the diff 46 | -- sometimes the entire diff is 0%, which looks like bad data 47 | AND SUM(CASE WHEN itemid IN (51146, 51200, 51244, 51245, 51254, 51256) THEN valuenum ELSE NULL END) > 0 48 | THEN 1 ELSE 0 END AS impute_abs 49 | 50 | FROM mimic_hosp.labevents le 51 | WHERE le.itemid IN 52 | ( 53 | 51146, -- basophils 54 | 52069, -- Absolute basophil count 55 | 51199, -- Eosinophil Count 56 | 51200, -- Eosinophils 57 | 52073, -- Absolute Eosinophil count 58 | 51244, -- Lymphocytes 59 | 51245, -- Lymphocytes, Percent 60 | 51133, -- Absolute Lymphocyte Count 61 | 52769, -- Absolute Lymphocyte Count 62 | 51253, -- Monocyte Count 63 | 51254, -- Monocytes 64 | 52074, -- Absolute Monocyte Count 65 | 51256, -- Neutrophils 66 | 52075, -- Absolute Neutrophil Count 67 | 51143, -- Atypical lymphocytes 68 | 51144, -- Bands (%) 69 | 51218, -- Granulocyte Count 70 | 52135, -- Immature granulocytes (%) 71 | 51251, -- Metamyelocytes 72 | 51257, -- Nucleated Red Cells 73 | 74 | -- wbc totals measured in K/uL 75 | 51300, 51301, 51755 76 | -- 52220 (wbcp) is percentage 77 | 78 | -- below are point of care tests which are extremely infrequent and usually low quality 79 | -- 51697, -- Neutrophils (mmol/L) 80 | 81 | -- below itemid do not have data as of MIMIC-IV v1.0 82 | -- 51536, -- Absolute Lymphocyte Count 83 | -- 51537, -- Absolute Neutrophil 84 | -- 51690, -- Lymphocytes 85 | -- 52151, -- NRBC 86 | ) 87 | AND valuenum IS NOT NULL 88 | -- differential values cannot be negative 89 | AND valuenum >= 0 90 | GROUP BY le.specimen_id 91 | ) 92 | SELECT 93 | subject_id, hadm_id, charttime, specimen_id 94 | 95 | , wbc 96 | -- impute absolute count if percentage & WBC is available 97 | , ROUND(cast(CASE 98 | WHEN basophils_abs IS NULL AND basophils IS NOT NULL AND impute_abs = 1 99 | THEN basophils * wbc 100 | ELSE basophils_abs 101 | END as numeric), 4) AS basophils_abs 102 | , ROUND(cast(CASE 103 | WHEN eosinophils_abs IS NULL AND eosinophils IS NOT NULL AND impute_abs = 1 104 | THEN eosinophils * wbc 105 | ELSE eosinophils_abs 106 | END as numeric), 4) AS eosinophils_abs 107 | , ROUND(cast(CASE 108 | WHEN lymphocytes_abs IS NULL AND lymphocytes IS NOT NULL AND impute_abs = 1 109 | THEN lymphocytes * wbc 110 | ELSE lymphocytes_abs 111 | END as numeric), 4) AS lymphocytes_abs 112 | , ROUND(cast(CASE 113 | WHEN monocytes_abs IS NULL AND monocytes IS NOT NULL AND impute_abs = 1 114 | THEN monocytes * wbc 115 | ELSE monocytes_abs 116 | END as numeric), 4) AS monocytes_abs 117 | , ROUND(cast(CASE 118 | WHEN neutrophils_abs IS NULL AND neutrophils IS NOT NULL AND impute_abs = 1 119 | THEN neutrophils * wbc 120 | ELSE neutrophils_abs 121 | END as numeric), 4) AS neutrophils_abs 122 | 123 | , basophils 124 | , eosinophils 125 | , lymphocytes 126 | , monocytes 127 | , neutrophils 128 | 129 | -- impute bands/blasts? 130 | , atypical_lymphocytes 131 | , bands 132 | , immature_granulocytes 133 | , metamyelocytes 134 | , nrbc 135 | FROM blood_diff 136 | ; 137 | -------------------------------------------------------------------------------- /concepts_PG_local/sepsis/suspicion_of_infection_pg.sql: -------------------------------------------------------------------------------- 1 | -- note this duplicates prescriptions 2 | -- each ICU stay in the same hospitalization will get a copy of all prescriptions for that hospitalization 3 | WITH ab_tbl AS 4 | ( 5 | select 6 | abx.subject_id, abx.hadm_id, abx.stay_id 7 | , abx.antibiotic 8 | , abx.starttime AS antibiotic_time 9 | -- date is used to match microbiology cultures with only date available 10 | , DATE_TRUNC('day' , abx.starttime) AS antibiotic_date 11 | , abx.stoptime AS antibiotic_stoptime 12 | -- create a unique identifier for each patient antibiotic 13 | , ROW_NUMBER() OVER 14 | ( 15 | PARTITION BY subject_id 16 | ORDER BY starttime, stoptime, antibiotic 17 | ) AS ab_id 18 | from mimiciv.antibiotic_mv abx 19 | ) 20 | , me as 21 | ( 22 | select micro_specimen_id 23 | -- the following columns are identical for all rows of the same micro_specimen_id 24 | -- these aggregates simply collapse duplicates down to 1 row 25 | , MAX(subject_id) AS subject_id 26 | , MAX(hadm_id) AS hadm_id 27 | , CAST(MAX(chartdate) AS DATE) AS chartdate 28 | , MAX(charttime) AS charttime 29 | , MAX(spec_type_desc) AS spec_type_desc 30 | , max(case when org_name is not null and org_name != '' then 1 else 0 end) as PositiveCulture 31 | from mimic_hosp.microbiologyevents 32 | group by micro_specimen_id 33 | ) 34 | -- culture followed by an antibiotic 35 | , me_then_ab AS 36 | ( 37 | select 38 | ab_tbl.subject_id 39 | , ab_tbl.hadm_id 40 | , ab_tbl.stay_id 41 | , ab_tbl.ab_id 42 | 43 | , me72.micro_specimen_id 44 | , coalesce(me72.charttime, CAST(me72.chartdate AS DATE)) as last72_charttime 45 | , me72.positiveculture as last72_positiveculture 46 | , me72.spec_type_desc as last72_specimen 47 | 48 | -- we will use this partition to select the earliest culture before this abx 49 | -- this ensures each antibiotic is only matched to a single culture 50 | -- and consequently we have 1 row per antibiotic 51 | , ROW_NUMBER() OVER 52 | ( 53 | PARTITION BY ab_tbl.subject_id, ab_tbl.ab_id 54 | ORDER BY me72.chartdate, me72.charttime NULLS LAST 55 | ) AS micro_seq 56 | from ab_tbl 57 | -- abx taken after culture, but no more than 72 hours after 58 | LEFT JOIN me me72 59 | on ab_tbl.subject_id = me72.subject_id 60 | and 61 | ( 62 | ( 63 | -- if charttime is available, use it 64 | me72.charttime is not null 65 | and ab_tbl.antibiotic_time > me72.charttime 66 | and ab_tbl.antibiotic_time <= DATE(me72.charttime + INTERVAL '72 HOUR') 67 | ) 68 | OR 69 | ( 70 | -- if charttime is not available, use chartdate 71 | me72.charttime is null 72 | and antibiotic_date >= me72.chartdate 73 | and antibiotic_date <= DATE(me72.chartdate + INTERVAL '3 DAY') 74 | ) 75 | ) 76 | ) 77 | , ab_then_me AS 78 | ( 79 | select 80 | ab_tbl.subject_id 81 | , ab_tbl.hadm_id 82 | , ab_tbl.stay_id 83 | , ab_tbl.ab_id 84 | 85 | , me24.micro_specimen_id 86 | , COALESCE(me24.charttime, CAST(me24.chartdate AS DATE)) as next24_charttime 87 | , me24.positiveculture as next24_positiveculture 88 | , me24.spec_type_desc as next24_specimen 89 | 90 | -- we will use this partition to select the earliest culture before this abx 91 | -- this ensures each antibiotic is only matched to a single culture 92 | -- and consequently we have 1 row per antibiotic 93 | , ROW_NUMBER() OVER 94 | ( 95 | PARTITION BY ab_tbl.subject_id, ab_tbl.ab_id 96 | ORDER BY me24.chartdate, me24.charttime NULLS LAST 97 | ) AS micro_seq 98 | from ab_tbl 99 | -- culture in subsequent 24 hours 100 | LEFT JOIN me me24 101 | on ab_tbl.subject_id = me24.subject_id 102 | and 103 | ( 104 | ( 105 | -- if charttime is available, use it 106 | me24.charttime is not null 107 | and ab_tbl.antibiotic_time >= DATE(me24.charttime - INTERVAL '24 HOUR') 108 | and ab_tbl.antibiotic_time < me24.charttime 109 | ) 110 | OR 111 | ( 112 | -- if charttime is not available, use chartdate 113 | me24.charttime is null 114 | and ab_tbl.antibiotic_date >= DATE(me24.chartdate - INTERVAL '1 DAY') 115 | and ab_tbl.antibiotic_date <= me24.chartdate 116 | ) 117 | ) 118 | ) 119 | SELECT 120 | ab_tbl.subject_id 121 | , ab_tbl.stay_id 122 | , ab_tbl.hadm_id 123 | , ab_tbl.ab_id 124 | , ab_tbl.antibiotic 125 | , ab_tbl.antibiotic_time 126 | 127 | , CASE 128 | WHEN last72_specimen IS NULL AND next24_specimen IS NULL 129 | THEN 0 130 | ELSE 1 131 | END AS suspected_infection 132 | -- time of suspected infection: 133 | -- (1) the culture time (if before antibiotic) 134 | -- (2) or the antibiotic time (if before culture) 135 | , CASE 136 | WHEN last72_specimen IS NULL AND next24_specimen IS NULL 137 | THEN NULL 138 | ELSE COALESCE(last72_charttime, antibiotic_time) 139 | END AS suspected_infection_time 140 | 141 | , COALESCE(last72_charttime, next24_charttime) AS culture_time 142 | 143 | -- the specimen that was cultured 144 | , COALESCE(last72_specimen, next24_specimen) AS specimen 145 | 146 | -- whether the cultured specimen ended up being positive or not 147 | , COALESCE(last72_positiveculture, next24_positiveculture) AS positive_culture 148 | 149 | FROM ab_tbl 150 | LEFT JOIN ab_then_me ab2me 151 | ON ab_tbl.subject_id = ab2me.subject_id 152 | AND ab_tbl.ab_id = ab2me.ab_id 153 | AND ab2me.micro_seq = 1 154 | LEFT JOIN me_then_ab me2ab 155 | ON ab_tbl.subject_id = me2ab.subject_id 156 | AND ab_tbl.ab_id = me2ab.ab_id 157 | AND me2ab.micro_seq = 1 158 | ; 159 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/blood_differential_mv.sql: -------------------------------------------------------------------------------- 1 | -- For reference, some common unit conversions: 2 | -- 10^9/L == K/uL == 10^3/uL 3 | 4 | CREATE MATERIALIZED VIEW mimiciv.blood_differential_mv AS 5 | 6 | WITH blood_diff AS 7 | ( 8 | SELECT 9 | MAX(subject_id) AS subject_id 10 | , MAX(hadm_id) AS hadm_id 11 | , MAX(charttime) AS charttime 12 | , le.specimen_id 13 | -- create one set of columns for percentages, and one set of columns for counts 14 | -- we harmonize all count units into K/uL == 10^9/L 15 | -- counts have an "_abs" suffix, percentages do not 16 | 17 | -- absolute counts 18 | , MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) AS wbc 19 | , MAX(CASE WHEN itemid = 52069 THEN valuenum ELSE NULL END) AS basophils_abs 20 | -- 52073 in K/uL, 51199 in #/uL 21 | , MAX(CASE WHEN itemid = 52073 THEN valuenum WHEN itemid = 51199 THEN valuenum / 1000.0 ELSE NULL END) AS eosinophils_abs 22 | -- 51133 in K/uL, 52769 in #/uL 23 | , MAX(CASE WHEN itemid = 51133 THEN valuenum WHEN itemid = 52769 THEN valuenum / 1000.0 ELSE NULL END) AS lymphocytes_abs 24 | -- 52074 in K/uL, 51253 in #/uL 25 | , MAX(CASE WHEN itemid = 52074 THEN valuenum WHEN itemid = 51253 THEN valuenum / 1000.0 ELSE NULL END) AS monocytes_abs 26 | , MAX(CASE WHEN itemid = 52075 THEN valuenum ELSE NULL END) AS neutrophils_abs 27 | -- convert from #/uL to K/uL 28 | , MAX(CASE WHEN itemid = 51218 THEN valuenum / 1000.0 ELSE NULL END) AS granulocytes_abs 29 | 30 | -- percentages, equal to cell count / white blood cell count 31 | , MAX(CASE WHEN itemid = 51146 THEN valuenum ELSE NULL END) AS basophils 32 | , MAX(CASE WHEN itemid = 51200 THEN valuenum ELSE NULL END) AS eosinophils 33 | , MAX(CASE WHEN itemid in (51244, 51245) THEN valuenum ELSE NULL END) AS lymphocytes 34 | , MAX(CASE WHEN itemid = 51254 THEN valuenum ELSE NULL END) AS monocytes 35 | , MAX(CASE WHEN itemid = 51256 THEN valuenum ELSE NULL END) AS neutrophils 36 | 37 | -- other cell count percentages 38 | , MAX(CASE WHEN itemid = 51143 THEN valuenum ELSE NULL END) AS atypical_lymphocytes 39 | , MAX(CASE WHEN itemid = 51144 THEN valuenum ELSE NULL END) AS bands 40 | , MAX(CASE WHEN itemid = 52135 THEN valuenum ELSE NULL END) AS immature_granulocytes 41 | , MAX(CASE WHEN itemid = 51251 THEN valuenum ELSE NULL END) AS metamyelocytes 42 | , MAX(CASE WHEN itemid = 51257 THEN valuenum ELSE NULL END) AS nrbc 43 | 44 | -- utility flags which determine whether imputation is possible 45 | , CASE 46 | -- WBC is available 47 | WHEN MAX(CASE WHEN itemid in (51300, 51301, 51755) THEN valuenum ELSE NULL END) > 0 48 | -- and we have at least one percentage from the diff 49 | -- sometimes the entire diff is 0%, which looks like bad data 50 | AND SUM(CASE WHEN itemid IN (51146, 51200, 51244, 51245, 51254, 51256) THEN valuenum ELSE NULL END) > 0 51 | THEN 1 ELSE 0 END AS impute_abs 52 | 53 | FROM mimic_hosp.labevents le 54 | WHERE le.itemid IN 55 | ( 56 | 51146, -- basophils 57 | 52069, -- Absolute basophil count 58 | 51199, -- Eosinophil Count 59 | 51200, -- Eosinophils 60 | 52073, -- Absolute Eosinophil count 61 | 51244, -- Lymphocytes 62 | 51245, -- Lymphocytes, Percent 63 | 51133, -- Absolute Lymphocyte Count 64 | 52769, -- Absolute Lymphocyte Count 65 | 51253, -- Monocyte Count 66 | 51254, -- Monocytes 67 | 52074, -- Absolute Monocyte Count 68 | 51256, -- Neutrophils 69 | 52075, -- Absolute Neutrophil Count 70 | 51143, -- Atypical lymphocytes 71 | 51144, -- Bands (%) 72 | 51218, -- Granulocyte Count 73 | 52135, -- Immature granulocytes (%) 74 | 51251, -- Metamyelocytes 75 | 51257, -- Nucleated Red Cells 76 | 77 | -- wbc totals measured in K/uL 78 | 51300, 51301, 51755 79 | -- 52220 (wbcp) is percentage 80 | 81 | -- below are point of care tests which are extremely infrequent and usually low quality 82 | -- 51697, -- Neutrophils (mmol/L) 83 | 84 | -- below itemid do not have data as of MIMIC-IV v1.0 85 | -- 51536, -- Absolute Lymphocyte Count 86 | -- 51537, -- Absolute Neutrophil 87 | -- 51690, -- Lymphocytes 88 | -- 52151, -- NRBC 89 | ) 90 | AND valuenum IS NOT NULL 91 | -- differential values cannot be negative 92 | AND valuenum >= 0 93 | GROUP BY le.specimen_id 94 | ) 95 | SELECT 96 | subject_id, hadm_id, charttime, specimen_id 97 | 98 | , wbc 99 | -- impute absolute count if percentage & WBC is available 100 | , ROUND(cast(CASE 101 | WHEN basophils_abs IS NULL AND basophils IS NOT NULL AND impute_abs = 1 102 | THEN basophils * wbc 103 | ELSE basophils_abs 104 | END as numeric), 4) AS basophils_abs 105 | , ROUND(cast(CASE 106 | WHEN eosinophils_abs IS NULL AND eosinophils IS NOT NULL AND impute_abs = 1 107 | THEN eosinophils * wbc 108 | ELSE eosinophils_abs 109 | END as numeric), 4) AS eosinophils_abs 110 | , ROUND(cast(CASE 111 | WHEN lymphocytes_abs IS NULL AND lymphocytes IS NOT NULL AND impute_abs = 1 112 | THEN lymphocytes * wbc 113 | ELSE lymphocytes_abs 114 | END as numeric), 4) AS lymphocytes_abs 115 | , ROUND(cast(CASE 116 | WHEN monocytes_abs IS NULL AND monocytes IS NOT NULL AND impute_abs = 1 117 | THEN monocytes * wbc 118 | ELSE monocytes_abs 119 | END as numeric), 4) AS monocytes_abs 120 | , ROUND(cast(CASE 121 | WHEN neutrophils_abs IS NULL AND neutrophils IS NOT NULL AND impute_abs = 1 122 | THEN neutrophils * wbc 123 | ELSE neutrophils_abs 124 | END as numeric), 4) AS neutrophils_abs 125 | 126 | , basophils 127 | , eosinophils 128 | , lymphocytes 129 | , monocytes 130 | , neutrophils 131 | 132 | -- impute bands/blasts? 133 | , atypical_lymphocytes 134 | , bands 135 | , immature_granulocytes 136 | , metamyelocytes 137 | , nrbc 138 | FROM blood_diff 139 | ; 140 | -------------------------------------------------------------------------------- /concepts_PG_local/treatment/ventilation_pg.sql: -------------------------------------------------------------------------------- 1 | -- Calculate duration of mechanical ventilation. 2 | -- Some useful cases for debugging: 3 | -- stay_id = 30019660 has a tracheostomy placed in the ICU 4 | -- stay_id = 30000117 has explicit documentation of extubation 5 | -- classify vent settings into modes 6 | WITH tm AS 7 | ( 8 | SELECT stay_id, charttime 9 | FROM mimiciv.ventilator_setting_mv 10 | UNION DISTINCT 11 | SELECT stay_id, charttime 12 | FROM mimiciv.oxygen_delivery_mv 13 | ) 14 | , vs AS 15 | ( 16 | SELECT tm.stay_id, tm.charttime 17 | -- source data columns, here for debug 18 | , o2_delivery_device_1 19 | , COALESCE(ventilator_mode, ventilator_mode_hamilton) AS vent_mode 20 | -- case statement determining the type of intervention 21 | -- done in order of priority: trach > mech vent > NIV > high flow > o2 22 | , CASE 23 | -- tracheostomy 24 | WHEN o2_delivery_device_1 IN 25 | ( 26 | 'Tracheostomy tube' 27 | -- 'Trach mask ' -- 16435 observations 28 | ) 29 | THEN 'Trach' 30 | -- mechanical ventilation 31 | WHEN o2_delivery_device_1 IN 32 | ( 33 | 'Endotracheal tube' 34 | ) 35 | OR ventilator_mode IN 36 | ( 37 | '(S) CMV', 38 | 'APRV', 39 | 'APRV/Biphasic+ApnPress', 40 | 'APRV/Biphasic+ApnVol', 41 | 'APV (cmv)', 42 | 'Ambient', 43 | 'Apnea Ventilation', 44 | 'CMV', 45 | 'CMV/ASSIST', 46 | 'CMV/ASSIST/AutoFlow', 47 | 'CMV/AutoFlow', 48 | 'CPAP/PPS', 49 | 'CPAP/PSV+Apn TCPL', 50 | 'CPAP/PSV+ApnPres', 51 | 'CPAP/PSV+ApnVol', 52 | 'MMV', 53 | 'MMV/AutoFlow', 54 | 'MMV/PSV', 55 | 'MMV/PSV/AutoFlow', 56 | 'P-CMV', 57 | 'PCV+', 58 | 'PCV+/PSV', 59 | 'PCV+Assist', 60 | 'PRES/AC', 61 | 'PRVC/AC', 62 | 'PRVC/SIMV', 63 | 'PSV/SBT', 64 | 'SIMV', 65 | 'SIMV/AutoFlow', 66 | 'SIMV/PRES', 67 | 'SIMV/PSV', 68 | 'SIMV/PSV/AutoFlow', 69 | 'SIMV/VOL', 70 | 'SYNCHRON MASTER', 71 | 'SYNCHRON SLAVE', 72 | 'VOL/AC' 73 | ) 74 | OR ventilator_mode_hamilton IN 75 | ( 76 | 'APRV', 77 | 'APV (cmv)', 78 | 'Ambient', 79 | '(S) CMV', 80 | 'P-CMV', 81 | 'SIMV', 82 | 'APV (simv)', 83 | 'P-SIMV', 84 | 'VS', 85 | 'ASV' 86 | ) 87 | THEN 'InvasiveVent' 88 | -- NIV 89 | WHEN o2_delivery_device_1 IN 90 | ( 91 | 'Bipap mask ', -- 8997 observations 92 | 'CPAP mask ' -- 5568 observations 93 | ) 94 | OR ventilator_mode_hamilton IN 95 | ( 96 | 'DuoPaP', 97 | 'NIV', 98 | 'NIV-ST' 99 | ) 100 | THEN 'NonInvasiveVent' 101 | -- high flow 102 | when o2_delivery_device_1 IN 103 | ( 104 | 'High flow neb', -- 10785 observations 105 | 'High flow nasal cannula' -- 925 observations 106 | ) 107 | THEN 'HighFlow' 108 | -- normal oxygen delivery 109 | WHEN o2_delivery_device_1 in 110 | ( 111 | 'Nasal cannula', -- 153714 observations 112 | 'Face tent', -- 24601 observations 113 | 'Aerosol-cool', -- 24560 observations 114 | 'Non-rebreather', -- 5182 observations 115 | 'Venti mask ', -- 1947 observations 116 | 'Medium conc mask ', -- 1888 observations 117 | 'T-piece', -- 1135 observations 118 | 'Ultrasonic neb', -- 9 observations 119 | 'Vapomist', -- 3 observations 120 | 'Oxymizer' -- 1301 observations 121 | ) 122 | THEN 'Oxygen' 123 | -- Not categorized: 124 | -- 'Other', 'None' 125 | ELSE NULL END AS ventilation_status 126 | FROM tm 127 | LEFT JOIN mimiciv.ventilator_setting_mv vs 128 | ON tm.stay_id = vs.stay_id 129 | AND tm.charttime = vs.charttime 130 | LEFT JOIN mimiciv.oxygen_delivery_mv od 131 | ON tm.stay_id = od.stay_id 132 | AND tm.charttime = od.charttime 133 | ) 134 | , vd0 AS 135 | ( 136 | SELECT 137 | stay_id, charttime 138 | -- source data columns, here for debug 139 | , o2_delivery_device_1 140 | , vent_mode 141 | -- carry over the previous charttime which had the same state 142 | , LAG(charttime, 1) OVER (PARTITION BY stay_id, ventilation_status ORDER BY charttime) AS charttime_lag 143 | -- bring back the next charttime, regardless of the state 144 | -- this will be used as the end time for state transitions 145 | , LEAD(charttime, 1) OVER w AS charttime_lead 146 | , ventilation_status 147 | , LAG(ventilation_status, 1) OVER w AS ventilation_status_lag 148 | FROM vs 149 | WHERE ventilation_status IS NOT NULL 150 | WINDOW w AS (PARTITION BY stay_id ORDER BY charttime) 151 | ) 152 | , vd1 as 153 | ( 154 | SELECT 155 | stay_id 156 | -- source data columns, here for debug 157 | , o2_delivery_device_1 158 | , vent_mode 159 | , charttime_lag 160 | , charttime 161 | , charttime_lead 162 | , ventilation_status 163 | 164 | -- calculate the time since the last event 165 | -- , DATETIME_DIFF(charttime, charttime_lag, MINUTE)/60 as ventduration 166 | , ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) as los_icu 167 | -- now we determine if the current ventilation status is "new", or continuing the previous 168 | , CASE 169 | -- a 14 hour gap always initiates a new event 170 | -- WHEN DATETIME_DIFF(charttime, charttime_lag, HOUR) >= 14 THEN 1 171 | WHEN ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) >= 14 THEN 1 172 | WHEN ventilation_status_lag IS NULL THEN 1 173 | -- not a new event if identical to the last row 174 | WHEN ventilation_status_lag != ventilation_status THEN 1 175 | ELSE 0 176 | END AS new_status 177 | FROM vd0 178 | ) 179 | , vd2 as 180 | ( 181 | SELECT vd1.* 182 | -- create a cumulative sum of the instances of new ventilation 183 | -- this results in a monotonic integer assigned to each instance of ventilation 184 | , SUM(new_status) OVER (PARTITION BY stay_id ORDER BY charttime) AS vent_num 185 | FROM vd1 186 | ) 187 | -- create the durations for each ventilation instance 188 | SELECT stay_id 189 | , MIN(charttime) AS starttime 190 | -- for the end time of the ventilation event, the time of the *next* setting 191 | -- i.e. if we go NIV -> O2, the end time of NIV is the first row with a documented O2 device 192 | -- ... unless it's been over 14 hours, in which case it's the last row with a documented NIV. 193 | , MAX( 194 | CASE 195 | WHEN charttime_lead IS NULL 196 | -- OR DATETIME_DIFF(charttime_lead, charttime, HOUR) >= 14 197 | OR ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) >= 14 198 | THEN charttime 199 | ELSE charttime_lead 200 | END 201 | ) AS endtime 202 | -- all rows with the same vent_num will have the same ventilation_status 203 | -- for efficiency, we use an aggregate here, but we could equally well group by this column 204 | , MAX(ventilation_status) AS ventilation_status 205 | FROM vd2 206 | GROUP BY stay_id, vent_num 207 | HAVING min(charttime) != max(charttime) 208 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/ventilation_mv.sql: -------------------------------------------------------------------------------- 1 | -- Calculate duration of mechanical ventilation. 2 | -- Some useful cases for debugging: 3 | -- stay_id = 30019660 has a tracheostomy placed in the ICU 4 | -- stay_id = 30000117 has explicit documentation of extubation 5 | -- classify vent settings into modes 6 | 7 | CREATE MATERIALIZED VIEW mimiciv.ventilation_mv AS 8 | 9 | WITH tm AS 10 | ( 11 | SELECT stay_id, charttime 12 | FROM mimiciv.ventilator_setting_mv 13 | UNION DISTINCT 14 | SELECT stay_id, charttime 15 | FROM mimiciv.oxygen_delivery_mv 16 | ) 17 | , vs AS 18 | ( 19 | SELECT tm.stay_id, tm.charttime 20 | -- source data columns, here for debug 21 | , o2_delivery_device_1 22 | , COALESCE(ventilator_mode, ventilator_mode_hamilton) AS vent_mode 23 | -- case statement determining the type of intervention 24 | -- done in order of priority: trach > mech vent > NIV > high flow > o2 25 | , CASE 26 | -- tracheostomy 27 | WHEN o2_delivery_device_1 IN 28 | ( 29 | 'Tracheostomy tube' 30 | -- 'Trach mask ' -- 16435 observations 31 | ) 32 | THEN 'Trach' 33 | -- mechanical ventilation 34 | WHEN o2_delivery_device_1 IN 35 | ( 36 | 'Endotracheal tube' 37 | ) 38 | OR ventilator_mode IN 39 | ( 40 | '(S) CMV', 41 | 'APRV', 42 | 'APRV/Biphasic+ApnPress', 43 | 'APRV/Biphasic+ApnVol', 44 | 'APV (cmv)', 45 | 'Ambient', 46 | 'Apnea Ventilation', 47 | 'CMV', 48 | 'CMV/ASSIST', 49 | 'CMV/ASSIST/AutoFlow', 50 | 'CMV/AutoFlow', 51 | 'CPAP/PPS', 52 | 'CPAP/PSV+Apn TCPL', 53 | 'CPAP/PSV+ApnPres', 54 | 'CPAP/PSV+ApnVol', 55 | 'MMV', 56 | 'MMV/AutoFlow', 57 | 'MMV/PSV', 58 | 'MMV/PSV/AutoFlow', 59 | 'P-CMV', 60 | 'PCV+', 61 | 'PCV+/PSV', 62 | 'PCV+Assist', 63 | 'PRES/AC', 64 | 'PRVC/AC', 65 | 'PRVC/SIMV', 66 | 'PSV/SBT', 67 | 'SIMV', 68 | 'SIMV/AutoFlow', 69 | 'SIMV/PRES', 70 | 'SIMV/PSV', 71 | 'SIMV/PSV/AutoFlow', 72 | 'SIMV/VOL', 73 | 'SYNCHRON MASTER', 74 | 'SYNCHRON SLAVE', 75 | 'VOL/AC' 76 | ) 77 | OR ventilator_mode_hamilton IN 78 | ( 79 | 'APRV', 80 | 'APV (cmv)', 81 | 'Ambient', 82 | '(S) CMV', 83 | 'P-CMV', 84 | 'SIMV', 85 | 'APV (simv)', 86 | 'P-SIMV', 87 | 'VS', 88 | 'ASV' 89 | ) 90 | THEN 'InvasiveVent' 91 | -- NIV 92 | WHEN o2_delivery_device_1 IN 93 | ( 94 | 'Bipap mask ', -- 8997 observations 95 | 'CPAP mask ' -- 5568 observations 96 | ) 97 | OR ventilator_mode_hamilton IN 98 | ( 99 | 'DuoPaP', 100 | 'NIV', 101 | 'NIV-ST' 102 | ) 103 | THEN 'NonInvasiveVent' 104 | -- high flow 105 | when o2_delivery_device_1 IN 106 | ( 107 | 'High flow neb', -- 10785 observations 108 | 'High flow nasal cannula' -- 925 observations 109 | ) 110 | THEN 'HighFlow' 111 | -- normal oxygen delivery 112 | WHEN o2_delivery_device_1 in 113 | ( 114 | 'Nasal cannula', -- 153714 observations 115 | 'Face tent', -- 24601 observations 116 | 'Aerosol-cool', -- 24560 observations 117 | 'Non-rebreather', -- 5182 observations 118 | 'Venti mask ', -- 1947 observations 119 | 'Medium conc mask ', -- 1888 observations 120 | 'T-piece', -- 1135 observations 121 | 'Ultrasonic neb', -- 9 observations 122 | 'Vapomist', -- 3 observations 123 | 'Oxymizer' -- 1301 observations 124 | ) 125 | THEN 'Oxygen' 126 | -- Not categorized: 127 | -- 'Other', 'None' 128 | ELSE NULL END AS ventilation_status 129 | FROM tm 130 | LEFT JOIN mimiciv.ventilator_setting_mv vs 131 | ON tm.stay_id = vs.stay_id 132 | AND tm.charttime = vs.charttime 133 | LEFT JOIN mimiciv.oxygen_delivery_mv od 134 | ON tm.stay_id = od.stay_id 135 | AND tm.charttime = od.charttime 136 | ) 137 | , vd0 AS 138 | ( 139 | SELECT 140 | stay_id, charttime 141 | -- source data columns, here for debug 142 | , o2_delivery_device_1 143 | , vent_mode 144 | -- carry over the previous charttime which had the same state 145 | , LAG(charttime, 1) OVER (PARTITION BY stay_id, ventilation_status ORDER BY charttime) AS charttime_lag 146 | -- bring back the next charttime, regardless of the state 147 | -- this will be used as the end time for state transitions 148 | , LEAD(charttime, 1) OVER w AS charttime_lead 149 | , ventilation_status 150 | , LAG(ventilation_status, 1) OVER w AS ventilation_status_lag 151 | FROM vs 152 | WHERE ventilation_status IS NOT NULL 153 | WINDOW w AS (PARTITION BY stay_id ORDER BY charttime) 154 | ) 155 | , vd1 as 156 | ( 157 | SELECT 158 | stay_id 159 | -- source data columns, here for debug 160 | , o2_delivery_device_1 161 | , vent_mode 162 | , charttime_lag 163 | , charttime 164 | , charttime_lead 165 | , ventilation_status 166 | 167 | -- calculate the time since the last event 168 | -- , DATETIME_DIFF(charttime, charttime_lag, MINUTE)/60 as ventduration 169 | , ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) as los_icu 170 | -- now we determine if the current ventilation status is "new", or continuing the previous 171 | , CASE 172 | -- a 14 hour gap always initiates a new event 173 | -- WHEN DATETIME_DIFF(charttime, charttime_lag, HOUR) >= 14 THEN 1 174 | WHEN ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) >= 14 THEN 1 175 | WHEN ventilation_status_lag IS NULL THEN 1 176 | -- not a new event if identical to the last row 177 | WHEN ventilation_status_lag != ventilation_status THEN 1 178 | ELSE 0 179 | END AS new_status 180 | FROM vd0 181 | ) 182 | , vd2 as 183 | ( 184 | SELECT vd1.* 185 | -- create a cumulative sum of the instances of new ventilation 186 | -- this results in a monotonic integer assigned to each instance of ventilation 187 | , SUM(new_status) OVER (PARTITION BY stay_id ORDER BY charttime) AS vent_num 188 | FROM vd1 189 | ) 190 | -- create the durations for each ventilation instance 191 | SELECT stay_id 192 | , MIN(charttime) AS starttime 193 | -- for the end time of the ventilation event, the time of the *next* setting 194 | -- i.e. if we go NIV -> O2, the end time of NIV is the first row with a documented O2 device 195 | -- ... unless it's been over 14 hours, in which case it's the last row with a documented NIV. 196 | , MAX( 197 | CASE 198 | WHEN charttime_lead IS NULL 199 | -- OR DATETIME_DIFF(charttime_lead, charttime, HOUR) >= 14 200 | OR ROUND(cast(extract (EPOCH FROM (charttime - charttime_lag)/3600) as numeric), 2) >= 14 201 | THEN charttime 202 | ELSE charttime_lead 203 | END 204 | ) AS endtime 205 | -- all rows with the same vent_num will have the same ventilation_status 206 | -- for efficiency, we use an aggregate here, but we could equally well group by this column 207 | , MAX(ventilation_status) AS ventilation_status 208 | FROM vd2 209 | GROUP BY stay_id, vent_num 210 | HAVING min(charttime) != max(charttime) 211 | ; -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_lab_pg.sql: -------------------------------------------------------------------------------- 1 | 2 | -- CREATE MATERIALIZED VIEW mimiciv.first_day_lab_mv AS 3 | 4 | WITH cbc AS 5 | ( 6 | SELECT 7 | ie.stay_id 8 | , MIN(hematocrit) as hematocrit_min 9 | , MAX(hematocrit) as hematocrit_max 10 | , MIN(hemoglobin) as hemoglobin_min 11 | , MAX(hemoglobin) as hemoglobin_max 12 | , MIN(platelet) as platelets_min 13 | , MAX(platelet) as platelets_max 14 | , MIN(wbc) as wbc_min 15 | , MAX(wbc) as wbc_max 16 | FROM mimic_icu.icustays ie 17 | LEFT JOIN mimiciv.complete_blood_count_mv le 18 | ON le.subject_id = ie.subject_id 19 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 20 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 21 | GROUP BY ie.stay_id 22 | ) 23 | , chem AS 24 | ( 25 | SELECT 26 | ie.stay_id 27 | , MIN(albumin) AS albumin_min, MAX(albumin) AS albumin_max 28 | , MIN(globulin) AS globulin_min, MAX(globulin) AS globulin_max 29 | , MIN(total_protein) AS total_protein_min, MAX(total_protein) AS total_protein_max 30 | , MIN(aniongap) AS aniongap_min, MAX(aniongap) AS aniongap_max 31 | , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max 32 | , MIN(bun) AS bun_min, MAX(bun) AS bun_max 33 | , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max 34 | , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max 35 | , MIN(creatinine) AS creatinine_min, MAX(creatinine) AS creatinine_max 36 | , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max 37 | , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max 38 | , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max 39 | FROM mimic_icu.icustays ie 40 | LEFT JOIN mimiciv.chemistry_mv le 41 | ON le.subject_id = ie.subject_id 42 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 43 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 44 | GROUP BY ie.stay_id 45 | ) 46 | , diff AS 47 | ( 48 | SELECT 49 | ie.stay_id 50 | , MIN(basophils_abs) AS abs_basophils_min, MAX(basophils_abs) AS abs_basophils_max 51 | , MIN(eosinophils_abs) AS abs_eosinophils_min, MAX(eosinophils_abs) AS abs_eosinophils_max 52 | , MIN(lymphocytes_abs) AS abs_lymphocytes_min, MAX(lymphocytes_abs) AS abs_lymphocytes_max 53 | , MIN(monocytes_abs) AS abs_monocytes_min, MAX(monocytes_abs) AS abs_monocytes_max 54 | , MIN(neutrophils_abs) AS abs_neutrophils_min, MAX(neutrophils_abs) AS abs_neutrophils_max 55 | -- , MIN(abs_basophils) AS abs_basophils_min, MAX(abs_basophils) AS abs_basophils_max 56 | -- , MIN(abs_eosinophils) AS abs_eosinophils_min, MAX(abs_eosinophils) AS abs_eosinophils_max 57 | -- , MIN(abs_lymphocytes) AS abs_lymphocytes_min, MAX(abs_lymphocytes) AS abs_lymphocytes_max 58 | -- , MIN(abs_monocytes) AS abs_monocytes_min, MAX(abs_monocytes) AS abs_monocytes_max 59 | -- , MIN(abs_neutrophils) AS abs_neutrophils_min, MAX(abs_neutrophils) AS abs_neutrophils_max 60 | , MIN(atypical_lymphocytes) AS atyps_min, MAX(atypical_lymphocytes) AS atyps_max 61 | , MIN(bands) AS bands_min, MAX(bands) AS bands_max 62 | , MIN(immature_granulocytes) AS imm_granulocytes_min, MAX(immature_granulocytes) AS imm_granulocytes_max 63 | , MIN(metamyelocytes) AS metas_min, MAX(metamyelocytes) AS metas_max 64 | , MIN(nrbc) AS nrbc_min, MAX(nrbc) AS nrbc_max 65 | FROM mimic_icu.icustays ie 66 | LEFT JOIN mimiciv.blood_differential_mv le 67 | ON le.subject_id = ie.subject_id 68 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 69 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 70 | GROUP BY ie.stay_id 71 | ) 72 | , coag AS 73 | ( 74 | SELECT 75 | ie.stay_id 76 | , MIN(d_dimer) AS d_dimer_min, MAX(d_dimer) AS d_dimer_max 77 | , MIN(fibrinogen) AS fibrinogen_min, MAX(fibrinogen) AS fibrinogen_max 78 | , MIN(thrombin) AS thrombin_min, MAX(thrombin) AS thrombin_max 79 | , MIN(inr) AS inr_min, MAX(inr) AS inr_max 80 | , MIN(pt) AS pt_min, MAX(pt) AS pt_max 81 | , MIN(ptt) AS ptt_min, MAX(ptt) AS ptt_max 82 | FROM mimic_icu.icustays ie 83 | LEFT JOIN mimiciv.coagulation_mv le 84 | ON le.subject_id = ie.subject_id 85 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 86 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 87 | GROUP BY ie.stay_id 88 | ) 89 | , enz AS 90 | ( 91 | SELECT 92 | ie.stay_id 93 | 94 | , MIN(alt) AS alt_min, MAX(alt) AS alt_max 95 | , MIN(alp) AS alp_min, MAX(alp) AS alp_max 96 | , MIN(ast) AS ast_min, MAX(ast) AS ast_max 97 | , MIN(amylase) AS amylase_min, MAX(amylase) AS amylase_max 98 | , MIN(bilirubin_total) AS bilirubin_total_min, MAX(bilirubin_total) AS bilirubin_total_max 99 | , MIN(bilirubin_direct) AS bilirubin_direct_min, MAX(bilirubin_direct) AS bilirubin_direct_max 100 | , MIN(bilirubin_indirect) AS bilirubin_indirect_min, MAX(bilirubin_indirect) AS bilirubin_indirect_max 101 | , MIN(ck_cpk) AS ck_cpk_min, MAX(ck_cpk) AS ck_cpk_max 102 | , MIN(ck_mb) AS ck_mb_min, MAX(ck_mb) AS ck_mb_max 103 | , MIN(ggt) AS ggt_min, MAX(ggt) AS ggt_max 104 | , MIN(ld_ldh) AS ld_ldh_min, MAX(ld_ldh) AS ld_ldh_max 105 | FROM mimic_icu.icustays ie 106 | LEFT JOIN mimiciv.enzyme_mv le 107 | ON le.subject_id = ie.subject_id 108 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 109 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 110 | GROUP BY ie.stay_id 111 | ) 112 | SELECT 113 | ie.subject_id 114 | , ie.stay_id 115 | -- complete blood count 116 | , hematocrit_min, hematocrit_max 117 | , hemoglobin_min, hemoglobin_max 118 | , platelets_min, platelets_max 119 | , wbc_min, wbc_max 120 | -- chemistry 121 | , albumin_min, albumin_max 122 | , globulin_min, globulin_max 123 | , total_protein_min, total_protein_max 124 | , aniongap_min, aniongap_max 125 | , bicarbonate_min, bicarbonate_max 126 | , bun_min, bun_max 127 | , calcium_min, calcium_max 128 | , chloride_min, chloride_max 129 | , creatinine_min, creatinine_max 130 | , glucose_min, glucose_max 131 | , sodium_min, sodium_max 132 | , potassium_min, potassium_max 133 | -- blood differential 134 | , abs_basophils_min, abs_basophils_max 135 | , abs_eosinophils_min, abs_eosinophils_max 136 | , abs_lymphocytes_min, abs_lymphocytes_max 137 | , abs_monocytes_min, abs_monocytes_max 138 | , abs_neutrophils_min, abs_neutrophils_max 139 | , atyps_min, atyps_max 140 | , bands_min, bands_max 141 | , imm_granulocytes_min, imm_granulocytes_max 142 | , metas_min, metas_max 143 | , nrbc_min, nrbc_max 144 | -- coagulation 145 | , d_dimer_min, d_dimer_max 146 | , fibrinogen_min, fibrinogen_max 147 | , thrombin_min, thrombin_max 148 | , inr_min, inr_max 149 | , pt_min, pt_max 150 | , ptt_min, ptt_max 151 | -- enzymes and bilirubin 152 | , alt_min, alt_max 153 | , alp_min, alp_max 154 | , ast_min, ast_max 155 | , amylase_min, amylase_max 156 | , bilirubin_total_min, bilirubin_total_max 157 | , bilirubin_direct_min, bilirubin_direct_max 158 | , bilirubin_indirect_min, bilirubin_indirect_max 159 | , ck_cpk_min, ck_cpk_max 160 | , ck_mb_min, ck_mb_max 161 | , ggt_min, ggt_max 162 | , ld_ldh_min, ld_ldh_max 163 | FROM mimic_icu.icustays ie 164 | LEFT JOIN cbc 165 | ON ie.stay_id = cbc.stay_id 166 | LEFT JOIN chem 167 | ON ie.stay_id = chem.stay_id 168 | LEFT JOIN diff 169 | ON ie.stay_id = diff.stay_id 170 | LEFT JOIN coag 171 | ON ie.stay_id = coag.stay_id 172 | LEFT JOIN enz 173 | ON ie.stay_id = enz.stay_id 174 | ; -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/first_day_lab_mv.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE MATERIALIZED VIEW mimiciv.first_day_lab_mv AS 3 | 4 | WITH cbc AS 5 | ( 6 | SELECT 7 | ie.stay_id 8 | , MIN(hematocrit) as hematocrit_min 9 | , MAX(hematocrit) as hematocrit_max 10 | , MIN(hemoglobin) as hemoglobin_min 11 | , MAX(hemoglobin) as hemoglobin_max 12 | , MIN(platelet) as platelets_min 13 | , MAX(platelet) as platelets_max 14 | , MIN(wbc) as wbc_min 15 | , MAX(wbc) as wbc_max 16 | FROM mimic_icu.icustays ie 17 | LEFT JOIN mimiciv.complete_blood_count_mv le 18 | ON le.subject_id = ie.subject_id 19 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 20 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 21 | GROUP BY ie.stay_id 22 | ) 23 | , chem AS 24 | ( 25 | SELECT 26 | ie.stay_id 27 | , MIN(albumin) AS albumin_min, MAX(albumin) AS albumin_max 28 | , MIN(globulin) AS globulin_min, MAX(globulin) AS globulin_max 29 | , MIN(total_protein) AS total_protein_min, MAX(total_protein) AS total_protein_max 30 | , MIN(aniongap) AS aniongap_min, MAX(aniongap) AS aniongap_max 31 | , MIN(bicarbonate) AS bicarbonate_min, MAX(bicarbonate) AS bicarbonate_max 32 | , MIN(bun) AS bun_min, MAX(bun) AS bun_max 33 | , MIN(calcium) AS calcium_min, MAX(calcium) AS calcium_max 34 | , MIN(chloride) AS chloride_min, MAX(chloride) AS chloride_max 35 | , MIN(creatinine) AS creatinine_min, MAX(creatinine) AS creatinine_max 36 | , MIN(glucose) AS glucose_min, MAX(glucose) AS glucose_max 37 | , MIN(sodium) AS sodium_min, MAX(sodium) AS sodium_max 38 | , MIN(potassium) AS potassium_min, MAX(potassium) AS potassium_max 39 | FROM mimic_icu.icustays ie 40 | LEFT JOIN mimiciv.chemistry_mv le 41 | ON le.subject_id = ie.subject_id 42 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 43 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 44 | GROUP BY ie.stay_id 45 | ) 46 | , diff AS 47 | ( 48 | SELECT 49 | ie.stay_id 50 | , MIN(basophils_abs) AS abs_basophils_min, MAX(basophils_abs) AS abs_basophils_max 51 | , MIN(eosinophils_abs) AS abs_eosinophils_min, MAX(eosinophils_abs) AS abs_eosinophils_max 52 | , MIN(lymphocytes_abs) AS abs_lymphocytes_min, MAX(lymphocytes_abs) AS abs_lymphocytes_max 53 | , MIN(monocytes_abs) AS abs_monocytes_min, MAX(monocytes_abs) AS abs_monocytes_max 54 | , MIN(neutrophils_abs) AS abs_neutrophils_min, MAX(neutrophils_abs) AS abs_neutrophils_max 55 | -- , MIN(abs_basophils) AS abs_basophils_min, MAX(abs_basophils) AS abs_basophils_max 56 | -- , MIN(abs_eosinophils) AS abs_eosinophils_min, MAX(abs_eosinophils) AS abs_eosinophils_max 57 | -- , MIN(abs_lymphocytes) AS abs_lymphocytes_min, MAX(abs_lymphocytes) AS abs_lymphocytes_max 58 | -- , MIN(abs_monocytes) AS abs_monocytes_min, MAX(abs_monocytes) AS abs_monocytes_max 59 | -- , MIN(abs_neutrophils) AS abs_neutrophils_min, MAX(abs_neutrophils) AS abs_neutrophils_max 60 | , MIN(atypical_lymphocytes) AS atyps_min, MAX(atypical_lymphocytes) AS atyps_max 61 | , MIN(bands) AS bands_min, MAX(bands) AS bands_max 62 | , MIN(immature_granulocytes) AS imm_granulocytes_min, MAX(immature_granulocytes) AS imm_granulocytes_max 63 | , MIN(metamyelocytes) AS metas_min, MAX(metamyelocytes) AS metas_max 64 | , MIN(nrbc) AS nrbc_min, MAX(nrbc) AS nrbc_max 65 | FROM mimic_icu.icustays ie 66 | LEFT JOIN mimiciv.blood_differential_mv le 67 | ON le.subject_id = ie.subject_id 68 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 69 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 70 | GROUP BY ie.stay_id 71 | ) 72 | , coag AS 73 | ( 74 | SELECT 75 | ie.stay_id 76 | , MIN(d_dimer) AS d_dimer_min, MAX(d_dimer) AS d_dimer_max 77 | , MIN(fibrinogen) AS fibrinogen_min, MAX(fibrinogen) AS fibrinogen_max 78 | , MIN(thrombin) AS thrombin_min, MAX(thrombin) AS thrombin_max 79 | , MIN(inr) AS inr_min, MAX(inr) AS inr_max 80 | , MIN(pt) AS pt_min, MAX(pt) AS pt_max 81 | , MIN(ptt) AS ptt_min, MAX(ptt) AS ptt_max 82 | FROM mimic_icu.icustays ie 83 | LEFT JOIN mimiciv.coagulation_mv le 84 | ON le.subject_id = ie.subject_id 85 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 86 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 87 | GROUP BY ie.stay_id 88 | ) 89 | , enz AS 90 | ( 91 | SELECT 92 | ie.stay_id 93 | 94 | , MIN(alt) AS alt_min, MAX(alt) AS alt_max 95 | , MIN(alp) AS alp_min, MAX(alp) AS alp_max 96 | , MIN(ast) AS ast_min, MAX(ast) AS ast_max 97 | , MIN(amylase) AS amylase_min, MAX(amylase) AS amylase_max 98 | , MIN(bilirubin_total) AS bilirubin_total_min, MAX(bilirubin_total) AS bilirubin_total_max 99 | , MIN(bilirubin_direct) AS bilirubin_direct_min, MAX(bilirubin_direct) AS bilirubin_direct_max 100 | , MIN(bilirubin_indirect) AS bilirubin_indirect_min, MAX(bilirubin_indirect) AS bilirubin_indirect_max 101 | , MIN(ck_cpk) AS ck_cpk_min, MAX(ck_cpk) AS ck_cpk_max 102 | , MIN(ck_mb) AS ck_mb_min, MAX(ck_mb) AS ck_mb_max 103 | , MIN(ggt) AS ggt_min, MAX(ggt) AS ggt_max 104 | , MIN(ld_ldh) AS ld_ldh_min, MAX(ld_ldh) AS ld_ldh_max 105 | FROM mimic_icu.icustays ie 106 | LEFT JOIN mimiciv.enzyme_mv le 107 | ON le.subject_id = ie.subject_id 108 | AND le.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 109 | AND le.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 110 | GROUP BY ie.stay_id 111 | ) 112 | SELECT 113 | ie.subject_id 114 | , ie.stay_id 115 | -- complete blood count 116 | , hematocrit_min, hematocrit_max 117 | , hemoglobin_min, hemoglobin_max 118 | , platelets_min, platelets_max 119 | , wbc_min, wbc_max 120 | -- chemistry 121 | , albumin_min, albumin_max 122 | , globulin_min, globulin_max 123 | , total_protein_min, total_protein_max 124 | , aniongap_min, aniongap_max 125 | , bicarbonate_min, bicarbonate_max 126 | , bun_min, bun_max 127 | , calcium_min, calcium_max 128 | , chloride_min, chloride_max 129 | , creatinine_min, creatinine_max 130 | , glucose_min, glucose_max 131 | , sodium_min, sodium_max 132 | , potassium_min, potassium_max 133 | -- blood differential 134 | , abs_basophils_min, abs_basophils_max 135 | , abs_eosinophils_min, abs_eosinophils_max 136 | , abs_lymphocytes_min, abs_lymphocytes_max 137 | , abs_monocytes_min, abs_monocytes_max 138 | , abs_neutrophils_min, abs_neutrophils_max 139 | , atyps_min, atyps_max 140 | , bands_min, bands_max 141 | , imm_granulocytes_min, imm_granulocytes_max 142 | , metas_min, metas_max 143 | , nrbc_min, nrbc_max 144 | -- coagulation 145 | , d_dimer_min, d_dimer_max 146 | , fibrinogen_min, fibrinogen_max 147 | , thrombin_min, thrombin_max 148 | , inr_min, inr_max 149 | , pt_min, pt_max 150 | , ptt_min, ptt_max 151 | -- enzymes and bilirubin 152 | , alt_min, alt_max 153 | , alp_min, alp_max 154 | , ast_min, ast_max 155 | , amylase_min, amylase_max 156 | , bilirubin_total_min, bilirubin_total_max 157 | , bilirubin_direct_min, bilirubin_direct_max 158 | , bilirubin_indirect_min, bilirubin_indirect_max 159 | , ck_cpk_min, ck_cpk_max 160 | , ck_mb_min, ck_mb_max 161 | , ggt_min, ggt_max 162 | , ld_ldh_min, ld_ldh_max 163 | FROM mimic_icu.icustays ie 164 | LEFT JOIN cbc 165 | ON ie.stay_id = cbc.stay_id 166 | LEFT JOIN chem 167 | ON ie.stay_id = chem.stay_id 168 | LEFT JOIN diff 169 | ON ie.stay_id = diff.stay_id 170 | LEFT JOIN coag 171 | ON ie.stay_id = coag.stay_id 172 | LEFT JOIN enz 173 | ON ie.stay_id = enz.stay_id 174 | ; -------------------------------------------------------------------------------- /concepts_PG_local/score/lods_pg.sql: -------------------------------------------------------------------------------- 1 | -- ------------------------------------------------------------------ 2 | -- Title: Logistic Organ Dysfunction Score (LODS) 3 | -- This query extracts the logistic organ dysfunction system. 4 | -- This score is a measure of organ failure in a patient. 5 | -- The score is calculated on the first day of each ICU patients' stay. 6 | -- ------------------------------------------------------------------ 7 | 8 | -- Reference for LODS: 9 | -- Le Gall, J. R., Klar, J., Lemeshow, S., Saulnier, F., Alberti, C., Artigas, A., & Teres, D. 10 | -- The Logistic Organ Dysfunction system: a new way to assess organ dysfunction in the intensive care unit. 11 | -- JAMA 276.10 (1996): 802-810. 12 | 13 | -- Variables used in LODS: 14 | -- GCS 15 | -- VITALS: Heart rate, systolic blood pressure 16 | -- FLAGS: ventilation/cpap 17 | -- IO: urine output 18 | -- LABS: blood urea nitrogen, WBC, bilirubin, creatinine, prothrombin time (PT), platelets 19 | -- ABG: PaO2 with associated FiO2 20 | 21 | -- Note: 22 | -- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate stay_ids. 23 | -- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients. 24 | 25 | -- extract CPAP from the "Oxygen Delivery Device" fields 26 | with cpap as 27 | ( 28 | select ie.stay_id 29 | , min(DATE(charttime - INTERVAL '1 HOUR')) as starttime 30 | , max(DATE(charttime + INTERVAL '4 HOUR')) as endtime 31 | , max(CASE 32 | WHEN lower(ce.value) LIKE '%cpap%' THEN 1 33 | WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1 34 | else 0 end) as cpap 35 | FROM mimic_icu.icustays ie 36 | inner join mimic_icu.chartevents ce 37 | on ie.stay_id = ce.stay_id 38 | and ce.charttime between ie.intime and DATE(ie.intime + INTERVAL '1 DAY') 39 | where itemid = 226732 40 | and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%') 41 | group by ie.stay_id 42 | ) 43 | , pafi1 as 44 | ( 45 | -- join blood gas to ventilation durations to determine if patient was vent 46 | -- also join to cpap table for the same purpose 47 | select ie.stay_id, bg.charttime 48 | , pao2fio2ratio 49 | , case when vd.stay_id is not null then 1 else 0 end as vent 50 | , case when cp.stay_id is not null then 1 else 0 end as cpap 51 | from mimiciv.bg_mv bg 52 | INNER JOIN mimic_icu.icustays ie 53 | ON bg.hadm_id = ie.hadm_id 54 | AND bg.charttime >= ie.intime AND bg.charttime < ie.outtime 55 | left join mimiciv.ventilation_mv vd 56 | on ie.stay_id = vd.stay_id 57 | and bg.charttime >= vd.starttime 58 | and bg.charttime <= vd.endtime 59 | and vd.ventilation_status = 'InvasiveVent' 60 | left join cpap cp 61 | on ie.stay_id = cp.stay_id 62 | and bg.charttime >= cp.starttime 63 | and bg.charttime <= cp.endtime 64 | ) 65 | , pafi2 as 66 | ( 67 | -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients* 68 | select stay_id 69 | , min(pao2fio2ratio) as pao2fio2_vent_min 70 | from pafi1 71 | where vent = 1 or cpap = 1 72 | group by stay_id 73 | ) 74 | , cohort as 75 | ( 76 | select ie.subject_id 77 | , ie.hadm_id 78 | , ie.stay_id 79 | , ie.intime 80 | , ie.outtime 81 | 82 | , gcs.gcs_min 83 | , vital.heart_rate_max 84 | , vital.heart_rate_min 85 | , vital.sbp_max 86 | , vital.sbp_min 87 | 88 | -- this value is non-null iff the patient is on vent/cpap 89 | , pf.pao2fio2_vent_min 90 | 91 | , labs.bun_max 92 | , labs.bun_min 93 | , labs.wbc_max 94 | , labs.wbc_min 95 | , labs.bilirubin_total_max AS bilirubin_max 96 | , labs.creatinine_max 97 | , labs.pt_min 98 | , labs.pt_max 99 | , labs.platelets_min AS platelet_min 100 | 101 | , uo.urineoutput 102 | 103 | FROM mimic_icu.icustays ie 104 | inner join mimic_core.admissions adm 105 | on ie.hadm_id = adm.hadm_id 106 | inner join mimic_core.patients pat 107 | on ie.subject_id = pat.subject_id 108 | 109 | -- join to above view to get pao2/fio2 ratio 110 | left join pafi2 pf 111 | on ie.stay_id = pf.stay_id 112 | 113 | -- join to custom tables to get more data.... 114 | left join mimiciv.first_day_gcs_mv gcs 115 | on ie.stay_id = gcs.stay_id 116 | left join mimiciv.first_day_vitalsign_mv vital 117 | on ie.stay_id = vital.stay_id 118 | left join mimiciv.first_day_urine_output_mv uo 119 | on ie.stay_id = uo.stay_id 120 | left join mimiciv.first_day_lab_mv labs 121 | on ie.stay_id = labs.stay_id 122 | ) 123 | , scorecomp as 124 | ( 125 | select 126 | cohort.* 127 | -- Below code calculates the component scores needed for SAPS 128 | 129 | -- neurologic 130 | , case 131 | when gcs_min is null then null 132 | when gcs_min < 3 then null -- erroneous value/on trach 133 | when gcs_min <= 5 then 5 134 | when gcs_min <= 8 then 3 135 | when gcs_min <= 13 then 1 136 | else 0 137 | end as neurologic 138 | 139 | -- cardiovascular 140 | , case 141 | when heart_rate_max is null 142 | and sbp_min is null then null 143 | when heart_rate_min < 30 then 5 144 | when sbp_min < 40 then 5 145 | when sbp_min < 70 then 3 146 | when sbp_max >= 270 then 3 147 | when heart_rate_max >= 140 then 1 148 | when sbp_max >= 240 then 1 149 | when sbp_min < 90 then 1 150 | else 0 151 | end as cardiovascular 152 | 153 | -- renal 154 | , case 155 | when bun_max is null 156 | or urineoutput is null 157 | or creatinine_max is null 158 | then null 159 | when urineoutput < 500.0 then 5 160 | when bun_max >= 56.0 then 5 161 | when creatinine_max >= 1.60 then 3 162 | when urineoutput < 750.0 then 3 163 | when bun_max >= 28.0 then 3 164 | when urineoutput >= 10000.0 then 3 165 | when creatinine_max >= 1.20 then 1 166 | when bun_max >= 17.0 then 1 167 | when bun_max >= 7.50 then 1 168 | else 0 169 | end as renal 170 | 171 | -- pulmonary 172 | , case 173 | when pao2fio2_vent_min is null then 0 174 | when pao2fio2_vent_min >= 150 then 1 175 | when pao2fio2_vent_min < 150 then 3 176 | else null 177 | end as pulmonary 178 | 179 | -- hematologic 180 | , case 181 | when wbc_max is null 182 | and platelet_min is null 183 | then null 184 | when wbc_min < 1.0 then 3 185 | when wbc_min < 2.5 then 1 186 | when platelet_min < 50.0 then 1 187 | when wbc_max >= 50.0 then 1 188 | else 0 189 | end as hematologic 190 | 191 | -- hepatic 192 | -- We have defined the "standard" PT as 12 seconds. 193 | -- This is an assumption and subsequent analyses may be affected by this assumption. 194 | , case 195 | when pt_max is null 196 | and bilirubin_max is null 197 | then null 198 | when bilirubin_max >= 2.0 then 1 199 | when pt_max > (12+3) then 1 200 | when pt_min < (12*0.25) then 1 201 | else 0 202 | end as hepatic 203 | 204 | from cohort 205 | ) 206 | select ie.subject_id, ie.hadm_id, ie.stay_id 207 | -- coalesce statements impute normal score of zero if data element is missing 208 | , coalesce(neurologic,0) 209 | + coalesce(cardiovascular,0) 210 | + coalesce(renal,0) 211 | + coalesce(pulmonary,0) 212 | + coalesce(hematologic,0) 213 | + coalesce(hepatic,0) 214 | as LODS 215 | , neurologic 216 | , cardiovascular 217 | , renal 218 | , pulmonary 219 | , hematologic 220 | , hepatic 221 | FROM mimic_icu.icustays ie 222 | left join scorecomp s 223 | on ie.stay_id = s.stay_id 224 | ; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MIMIC IV-Windows - installations 2 | 3 | This is a repository to install MIMIC 4 in PostgreSQL a Windows environment, and then add materialised views of common SQL searches. 4 | The first part is reasonably straight forward, and is covered in various detail on other pages, which will be linked. 5 | The second part, using supplied SQL code to perform common searches, is more challenging, particularly as a number of SQL dialects have been used, along with a Cloud based mimic_derived database. 6 | To simplify this for Windows users, this links to a straight forward Windows installation of Postgres and PGadmin on a local machine, and building the dataset from the SQL command line. 7 | I have then altered the SQL code to work natively within PGAdmin, to completely build the dataset and materialised views on the local machine (or a stand alone local/Cloud VM). 8 | 9 | ## VM considerations 10 | If you are creating a VM to specifically host this, a few considerations. 11 | 1. If you place the full database is on the primary disk, you will need more than the usual 128gb of storage. You can do this initially when creating the drive, or add additional space (which in some VMs needs to be manually connected to the primary partition - go in to disk management and click on primary partition and select 'expand'). 12 | 2. Separating data and processing drives is often considered good practice, however for this may only provide a small advantage, with a concomitant increase in complexity. It works fine all hosted on a single disk. 13 | 3. You will note when creating both the database and the materialized views there is often 100% disk utilisation - so ensure you have good quality SSDs. 14 | 4. Temporary separate storage for the source files is useful when building the datasets. 15 | 5. Postgres processing is predominantly a few threads only, so a smaller number of CPU cores will work fine. 16 | 17 | ## Install Postgres 18 | And standard installation is all you need, and thus the initial instructions from here work fine (https://www.programmersought.com/article/21858700192/ ). Version 13 works with MIMIC IV, and the included version of PGAdmin also. 19 | Make sure you remember the Postgres username and password. Sticking with the usual defaults ('postgres' as user, 'postgres' as password) is OK in the Windows environment (and less likely to be forgotten). When you first open PGAdmin you will be asked for this master password. 20 | 21 | ## Install 7-Zip 22 | next install 7-zip (https://www.7-zip.org/) (this works fine with the supplied compressed MIMIC files). As per the link above, make sure you keep a note of the installation directory, and then add the path to you environment variables (in the Windows search box type 'environment', 'edit system variables', click on 'environment variables', click on 'path', click on 'edit' and add the path for 7-zip. 23 | It is worth checking the path has been registered before you start installing the database. Simply open a command window (Cmd) and type 7z - you should get a series of instructions about 7-zip. 24 | 25 | ## Download the MIMIC files. 26 | Note that these are fairly large files (around 7Gb total), so you will need both space to store them, and bandwidth. Even with good Cloud connections the download speeds are not high. 27 | IF you go to the MIMIC IV paper on physionet (https://physionet.org/content/mimiciv/1.0/) and log in to your account, you will find a link at the bottom to download the ZIP file (https://physionet.org/content/mimiciv/get-zip/1.0/). When finished downloading, unzip it in a directory that is easy to find, and with a short file path (to decrease typing and chance of errors!). Placing it on a separate drive to Postgres will help database load times. 28 | You will also need the MIMIC IV files from Github, linked here https://github.com/MIT-LCP/mimic-iv. Download these as a zip file (or clone using Git/Github desktop) and place where you can find them easily - usally on the same drive as the compressed csv files. You will initially need the files to build postgres (https://github.com/MIT-LCP/mimic-iv/tree/master/buildmimic/postgres). The 'concepts' are there also, noting that not all work with Postgres on Windows (and therefore I've re-written them and included them in this repository). 29 | 30 | ## Build the database 31 | This is often seen as the confusing part, as it needs some command line work. However if you use the SQL shell/command box, it becomes somewhat more straight forward. 32 | Then follwo the instructions here https://www.programmersought.com/article/97578529676/ - copy and paste in to the SQL shell, careful to follow the sequence. 33 | The basic sequence is: 34 | 1. log in to the server (accept the default by simply pressing 'enter' until asked for the password, then 'postgres' as above if you have kept this 35 | 2. create the database, and switch to it (CREATE DATABASE mimic OWNER postgres;) (\c mimic;) 36 | 3. create a schema to get started (CREATE SCHEMA mimiciv;) - you will use this later when building the materialised views 37 | 4. set a search path (set search_path to mimiciv;) - note you will need to repeat this if you get stuck and log out. 38 | 5. create the tables and schema (\i E:/postgres/create.sql) - make sure this is the correct directory for you 39 | 6. set to stop on error (\set ON_ERROR_STOP 1) 40 | 7. set the direcotry where your compressed mimic files are stored (\set mimic_data_dir 'E:/postgres/MIMICIV') - this directory is referenced in the build sql files. Make sure that you change this to where your files are stored. Note that it is also important that you keep the original sub-directory structure of the downloaded zip file containing the MIMIC data files. 41 | 8. now build the database (\i E:/postgres/load_7z.sql) - again make sure you have the right directory for your files here. 42 | 9. Wait...... It takes 1.5-2 hours, depending on your computer and drive speed. Some tables take >20min to build - chartevents has over 300 million rows, so understandable. There are 27 tables to build. You will be returned to the command line when build is complete. 43 | 10. Now build the indexes (\i E:/postgres/index.sql). Again this will take considerable time - 20-30 min. 44 | 11. Once completed, close the SQL window, open PGAdmin, log in to the database, and check everything is there. To check it is working, simply right-click on any of the tables, and look at the top 100 rows (it will create a simple SELECT statement). 45 | 12. Well done! 46 | 47 | # Using the Concepts 48 | The concepts included in the normal downloads (https://github.com/MIT-LCP/mimic-iv) are a series of SQL files that have been written to help with some of the more standard questions - e.g. use of vasopressors or antibiotics. These have been brought together from a number of sources, so not all the SQL code works within Postgres (yes, there are different 'dialects' of SQL). 49 | Also, a number of these files reference 'mimic_derived' - a database written from the original MIMIC that included many of the queries, to allow secondary and tertiary queries to occur of the dataset. The MIMIC-derived dataset is not available for MIMIC-IV. However, the functionality can be reproduced by using materialised views within MIMIC IV, and I have included the code in this repo (in fact the main reason for this repo). 50 | Note that given that some of the views build on other views, it is important to run these initially in order. Once these views are created, you can then go back to the primary SQL queries and run these, along with modifications as you wish. 51 | I have chosen to use materialised views as some of the base queries take 10-20 min to run - so better in a view. Given that MIMIC is often accessed in a time-limited environment (datathon), the time saving can be significant. 52 | 53 | The order for the materialized views is: 54 | - first group:Age_mv, antibiotics_mv, bg_mv, bg_pg_mv, blood_differential_mv, chemistry_mv, Coagulation_mv, complete_blood_count_mv, dobutamine_mv, dopamine_mv, enzyme_mv,Epinephrine_mv, gcs_mv, height_mv, icu_times_mv, kdigo_creatinine_mv, norepinephrine_mv, Oxygen_delivery_mv, rrt_mv, urine_output_mv, ventilator_setting_mv, vital_sign_mv, weight_durations_mv 55 | - second group:First_day_bg_art_mv, First_day_gcs_mv, first-day_lab_mv, first_day_rrt_mv, first_day_urine_output_mv, first_day_vitalsign_mv, kdigo_uo_mv, urine_output_rate_mv, ventilation_mv 56 | 57 | All of these queries have been tested and run within a local instance of Postgres 13, using PGAdmin, on a Windows machine, so hopefully these all work for you also. 58 | 59 | Note that there are still a few queries that I have not managed to translate across, namely icu_stay_hourly, sofa (that relies on it), and sepsis3 (that relies on sofa). 60 | 61 | -------------------------------------------------------------------------------- /concepts_PG_local/firstday/first_day_sofa_pg.sql: -------------------------------------------------------------------------------- 1 | -- ------------------------------------------------------------------ 2 | -- Title: Sequential Organ Failure Assessment (SOFA) 3 | -- This query extracts the sequential organ failure assessment (formally: sepsis-related organ failure assessment). 4 | -- This score is a measure of organ failure for patients in the ICU. 5 | -- The score is calculated on the first day of each ICU patients' stay. 6 | -- ------------------------------------------------------------------ 7 | 8 | -- Reference for SOFA: 9 | -- Jean-Louis Vincent, Rui Moreno, Jukka Takala, Sheila Willatts, Arnaldo De Mendonça, 10 | -- Hajo Bruining, C. K. Reinhart, Peter M Suter, and L. G. Thijs. 11 | -- "The SOFA (Sepsis-related Organ Failure Assessment) score to describe organ dysfunction/failure." 12 | -- Intensive care medicine 22, no. 7 (1996): 707-710. 13 | 14 | -- Variables used in SOFA: 15 | -- GCS, MAP, FiO2, Ventilation status (sourced from CHARTEVENTS) 16 | -- Creatinine, Bilirubin, FiO2, PaO2, Platelets (sourced from LABEVENTS) 17 | -- Dopamine, Dobutamine, Epinephrine, Norepinephrine (sourced from INPUTEVENTS) 18 | -- Urine output (sourced from OUTPUTEVENTS) 19 | 20 | -- The following views required to run this query: 21 | -- 1) first_day_urine_output 22 | -- 2) first_day_vitalsign 23 | -- 3) first_day_gcs 24 | -- 4) first_day_lab 25 | -- 5) first_day_bg_art 26 | -- 6) ventdurations 27 | 28 | -- extract drug rates from derived vasopressor tables 29 | with vaso_stg as 30 | ( 31 | select ie.stay_id, 'norepinephrine' AS treatment, vaso_rate as rate 32 | FROM mimic_icu.icustays ie 33 | INNER JOIN mimiciv.norepinephrine_mv mv 34 | ON ie.stay_id = mv.stay_id 35 | AND mv.starttime >= DATE(ie.intime - INTERVAL '6 HOURS') 36 | AND mv.starttime <= DATE(ie.intime + INTERVAL '1 DAY') 37 | UNION ALL 38 | select ie.stay_id, 'epinephrine' AS treatment, vaso_rate as rate 39 | FROM mimic_icu.icustays ie 40 | INNER JOIN mimiciv.epinephrine_mv mv 41 | ON ie.stay_id = mv.stay_id 42 | AND mv.starttime >= DATE(ie.intime - INTERVAL '6 HOURS') 43 | AND mv.starttime <= DATE(ie.intime + INTERVAL '1 DAY') 44 | UNION ALL 45 | select ie.stay_id, 'dobutamine' AS treatment, vaso_rate as rate 46 | FROM mimic_icu.icustays ie 47 | INNER JOIN mimiciv.dobutamine_mv mv 48 | ON ie.stay_id = mv.stay_id 49 | AND mv.starttime >= DATE(ie.intime - INTERVAL '6 HOURS') 50 | AND mv.starttime <= DATE(ie.intime + INTERVAL '1 DAY') 51 | UNION ALL 52 | select ie.stay_id, 'dopamine' AS treatment, vaso_rate as rate 53 | FROM mimic_icu.icustays ie 54 | INNER JOIN mimiciv.dopamine_mv mv 55 | ON ie.stay_id = mv.stay_id 56 | AND mv.starttime >= DATE(ie.intime - INTERVAL '6 HOURS') 57 | AND mv.starttime <= DATE(ie.intime + INTERVAL '1 DAY') 58 | ) 59 | , vaso_mv AS 60 | ( 61 | SELECT 62 | ie.stay_id 63 | , max(CASE WHEN treatment = 'norepinephrine' THEN rate ELSE NULL END) as rate_norepinephrine 64 | , max(CASE WHEN treatment = 'epinephrine' THEN rate ELSE NULL END) as rate_epinephrine 65 | , max(CASE WHEN treatment = 'dopamine' THEN rate ELSE NULL END) as rate_dopamine 66 | , max(CASE WHEN treatment = 'dobutamine' THEN rate ELSE NULL END) as rate_dobutamine 67 | from mimic_icu.icustays ie 68 | LEFT JOIN vaso_stg v 69 | ON ie.stay_id = v.stay_id 70 | GROUP BY ie.stay_id 71 | ) 72 | , pafi1 as 73 | ( 74 | -- join blood gas to ventilation durations to determine if patient was vent 75 | select ie.stay_id, bg.charttime 76 | , bg.pao2fio2ratio 77 | , case when vd.stay_id is not null then 1 else 0 end as IsVent 78 | from mimic_icu.icustays ie 79 | LEFT JOIN mimiciv.bg_mv bg 80 | ON ie.subject_id = bg.subject_id 81 | AND bg.charttime >= DATE(ie.intime - INTERVAL '6 HOURS') 82 | AND bg.charttime <= DATE(ie.intime + INTERVAL '1 DAY') 83 | LEFT JOIN mimiciv.ventilation_mv vd 84 | ON ie.stay_id = vd.stay_id 85 | AND bg.charttime >= vd.starttime 86 | AND bg.charttime <= vd.endtime 87 | AND vd.ventilation_status = 'InvasiveVent' 88 | ) 89 | , pafi2 as 90 | ( 91 | -- because pafi has an interaction between vent/PaO2:FiO2, we need two columns for the score 92 | -- it can happen that the lowest unventilated PaO2/FiO2 is 68, but the lowest ventilated PaO2/FiO2 is 120 93 | -- in this case, the SOFA score is 3, *not* 4. 94 | select stay_id 95 | , min(case when IsVent = 0 then pao2fio2ratio else null end) as PaO2FiO2_novent_min 96 | , min(case when IsVent = 1 then pao2fio2ratio else null end) as PaO2FiO2_vent_min 97 | from pafi1 98 | group by stay_id 99 | ) 100 | -- Aggregate the components for the score 101 | , scorecomp as 102 | ( 103 | select ie.stay_id 104 | , v.mbp_min 105 | , mv.rate_norepinephrine 106 | , mv.rate_epinephrine 107 | , mv.rate_dopamine 108 | , mv.rate_dobutamine 109 | 110 | , l.creatinine_max 111 | , l.bilirubin_total_max as bilirubin_max 112 | , l.platelets_min as platelet_min 113 | 114 | , pf.PaO2FiO2_novent_min 115 | , pf.PaO2FiO2_vent_min 116 | 117 | , uo.UrineOutput 118 | 119 | , gcs.gcs_min 120 | from mimic_icu.icustays ie 121 | left join vaso_mv mv 122 | on ie.stay_id = mv.stay_id 123 | left join pafi2 pf 124 | on ie.stay_id = pf.stay_id 125 | left join mimiciv.first_day_vitalsign_mv v 126 | on ie.stay_id = v.stay_id 127 | left join mimiciv.first_day_lab_mv l 128 | on ie.stay_id = l.stay_id 129 | left join mimiciv.first_day_urine_output_mv uo 130 | on ie.stay_id = uo.stay_id 131 | left join mimiciv.first_day_gcs_mv gcs 132 | on ie.stay_id = gcs.stay_id 133 | ) 134 | , scorecalc as 135 | ( 136 | -- Calculate the final score 137 | -- note that if the underlying data is missing, the component is null 138 | -- eventually these are treated as 0 (normal), but knowing when data is missing is useful for debugging 139 | select stay_id 140 | -- Respiration 141 | , case 142 | when PaO2FiO2_vent_min < 100 then 4 143 | when PaO2FiO2_vent_min < 200 then 3 144 | when PaO2FiO2_novent_min < 300 then 2 145 | when PaO2FiO2_novent_min < 400 then 1 146 | when coalesce(PaO2FiO2_vent_min, PaO2FiO2_novent_min) is null then null 147 | else 0 148 | end as respiration 149 | 150 | -- Coagulation 151 | , case 152 | when platelet_min < 20 then 4 153 | when platelet_min < 50 then 3 154 | when platelet_min < 100 then 2 155 | when platelet_min < 150 then 1 156 | when platelet_min is null then null 157 | else 0 158 | end as coagulation 159 | 160 | -- Liver 161 | , case 162 | -- Bilirubin checks in mg/dL 163 | when bilirubin_max >= 12.0 then 4 164 | when bilirubin_max >= 6.0 then 3 165 | when bilirubin_max >= 2.0 then 2 166 | when bilirubin_max >= 1.2 then 1 167 | when bilirubin_max is null then null 168 | else 0 169 | end as liver 170 | 171 | -- Cardiovascular 172 | , case 173 | when rate_dopamine > 15 or rate_epinephrine > 0.1 or rate_norepinephrine > 0.1 then 4 174 | when rate_dopamine > 5 or rate_epinephrine <= 0.1 or rate_norepinephrine <= 0.1 then 3 175 | when rate_dopamine > 0 or rate_dobutamine > 0 then 2 176 | when mbp_min < 70 then 1 177 | when coalesce(mbp_min, rate_dopamine, rate_dobutamine, rate_epinephrine, rate_norepinephrine) is null then null 178 | else 0 179 | end as cardiovascular 180 | 181 | -- Neurological failure (GCS) 182 | , case 183 | when (gcs_min >= 13 and gcs_min <= 14) then 1 184 | when (gcs_min >= 10 and gcs_min <= 12) then 2 185 | when (gcs_min >= 6 and gcs_min <= 9) then 3 186 | when gcs_min < 6 then 4 187 | when gcs_min is null then null 188 | else 0 end 189 | as cns 190 | 191 | -- Renal failure - high creatinine or low urine output 192 | , case 193 | when (creatinine_max >= 5.0) then 4 194 | when UrineOutput < 200 then 4 195 | when (creatinine_max >= 3.5 and creatinine_max < 5.0) then 3 196 | when UrineOutput < 500 then 3 197 | when (creatinine_max >= 2.0 and creatinine_max < 3.5) then 2 198 | when (creatinine_max >= 1.2 and creatinine_max < 2.0) then 1 199 | when coalesce(UrineOutput, creatinine_max) is null then null 200 | else 0 end 201 | as renal 202 | from scorecomp 203 | ) 204 | select ie.subject_id, ie.hadm_id, ie.stay_id 205 | -- Combine all the scores to get SOFA 206 | -- Impute 0 if the score is missing 207 | , coalesce(respiration,0) 208 | + coalesce(coagulation,0) 209 | + coalesce(liver,0) 210 | + coalesce(cardiovascular,0) 211 | + coalesce(cns,0) 212 | + coalesce(renal,0) 213 | as SOFA 214 | , respiration 215 | , coagulation 216 | , liver 217 | , cardiovascular 218 | , cns 219 | , renal 220 | from mimic_icu.icustays ie 221 | left join scorecalc s 222 | on ie.stay_id = s.stay_id 223 | ; -------------------------------------------------------------------------------- /concepts_PG_local/measurement/bg_pg.sql: -------------------------------------------------------------------------------- 1 | -- The aim of this query is to pivot entries related to blood gases 2 | -- which were found in LABEVENTS 3 | WITH bg AS 4 | ( 5 | select 6 | -- specimen_id only ever has 1 measurement for each itemid 7 | -- so, we may simply collapse rows using MAX() 8 | MAX(subject_id) AS subject_id 9 | , MAX(hadm_id) AS hadm_id 10 | , MAX(charttime) AS charttime 11 | -- specimen_id *may* have different storetimes, so this is taking the latest 12 | , MAX(storetime) AS storetime 13 | , le.specimen_id 14 | , MAX(CASE WHEN itemid = 52028 THEN value ELSE NULL END) AS specimen 15 | , MAX(CASE WHEN itemid = 50801 THEN valuenum ELSE NULL END) AS aado2 16 | , MAX(CASE WHEN itemid = 50802 THEN valuenum ELSE NULL END) AS baseexcess 17 | , MAX(CASE WHEN itemid = 50803 THEN valuenum ELSE NULL END) AS bicarbonate 18 | , MAX(CASE WHEN itemid = 50804 THEN valuenum ELSE NULL END) AS totalco2 19 | , MAX(CASE WHEN itemid = 50805 THEN valuenum ELSE NULL END) AS carboxyhemoglobin 20 | , MAX(CASE WHEN itemid = 50806 THEN valuenum ELSE NULL END) AS chloride 21 | , MAX(CASE WHEN itemid = 50808 THEN valuenum ELSE NULL END) AS calcium 22 | , MAX(CASE WHEN itemid = 50809 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose 23 | , MAX(CASE WHEN itemid = 50810 and valuenum <= 100 THEN valuenum ELSE NULL END) AS hematocrit 24 | , MAX(CASE WHEN itemid = 50811 THEN valuenum ELSE NULL END) AS hemoglobin 25 | , MAX(CASE WHEN itemid = 50813 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS lactate 26 | , MAX(CASE WHEN itemid = 50814 THEN valuenum ELSE NULL END) AS methemoglobin 27 | , MAX(CASE WHEN itemid = 50815 THEN valuenum ELSE NULL END) AS o2flow 28 | -- fix a common unit conversion error for fio2 29 | -- atmospheric o2 is 20.89%, so any value <= 20 is unphysiologic 30 | -- usually this is a misplaced O2 flow measurement 31 | , MAX(CASE WHEN itemid = 50816 THEN 32 | CASE 33 | WHEN valuenum > 20 AND valuenum <= 100 THEN valuenum 34 | WHEN valuenum > 0.2 AND valuenum <= 1.0 THEN valuenum*100.0 35 | ELSE NULL END 36 | ELSE NULL END) AS fio2 37 | , MAX(CASE WHEN itemid = 50817 AND valuenum <= 100 THEN valuenum ELSE NULL END) AS so2 38 | , MAX(CASE WHEN itemid = 50818 THEN valuenum ELSE NULL END) AS pco2 39 | , MAX(CASE WHEN itemid = 50819 THEN valuenum ELSE NULL END) AS peep 40 | , MAX(CASE WHEN itemid = 50820 THEN valuenum ELSE NULL END) AS ph 41 | , MAX(CASE WHEN itemid = 50821 THEN valuenum ELSE NULL END) AS po2 42 | , MAX(CASE WHEN itemid = 50822 THEN valuenum ELSE NULL END) AS potassium 43 | , MAX(CASE WHEN itemid = 50823 THEN valuenum ELSE NULL END) AS requiredo2 44 | , MAX(CASE WHEN itemid = 50824 THEN valuenum ELSE NULL END) AS sodium 45 | , MAX(CASE WHEN itemid = 50825 THEN valuenum ELSE NULL END) AS temperature 46 | , MAX(CASE WHEN itemid = 50807 THEN value ELSE NULL END) AS comments 47 | FROM mimic_hosp.labevents le 48 | where le.ITEMID in 49 | -- blood gases 50 | ( 51 | 52028 -- specimen 52 | , 50801 -- aado2 53 | , 50802 -- base excess 54 | , 50803 -- bicarb 55 | , 50804 -- calc tot co2 56 | , 50805 -- carboxyhgb 57 | , 50806 -- chloride 58 | -- , 52390 -- chloride, WB CL- 59 | , 50807 -- comments 60 | , 50808 -- free calcium 61 | , 50809 -- glucose 62 | , 50810 -- hct 63 | , 50811 -- hgb 64 | , 50813 -- lactate 65 | , 50814 -- methemoglobin 66 | , 50815 -- o2 flow 67 | , 50816 -- fio2 68 | , 50817 -- o2 sat 69 | , 50818 -- pco2 70 | , 50819 -- peep 71 | , 50820 -- pH 72 | , 50821 -- pO2 73 | , 50822 -- potassium 74 | -- , 52408 -- potassium, WB K+ 75 | , 50823 -- required O2 76 | , 50824 -- sodium 77 | -- , 52411 -- sodium, WB NA + 78 | , 50825 -- temperature 79 | ) 80 | GROUP BY le.specimen_id 81 | ) 82 | , stg_spo2 as 83 | ( 84 | select subject_id, charttime 85 | -- avg here is just used to group SpO2 by charttime 86 | , AVG(valuenum) as SpO2 87 | FROM mimic_icu.chartevents 88 | where ITEMID = 220277 -- O2 saturation pulseoxymetry 89 | and valuenum > 0 and valuenum <= 100 90 | group by subject_id, charttime 91 | ) 92 | , stg_fio2 as 93 | ( 94 | select subject_id, charttime 95 | -- pre-process the FiO2s to ensure they are between 21-100% 96 | , max( 97 | case 98 | when valuenum > 0.2 and valuenum <= 1 99 | then valuenum * 100 100 | -- improperly input data - looks like O2 flow in litres 101 | when valuenum > 1 and valuenum < 20 102 | then null 103 | when valuenum >= 20 and valuenum <= 100 104 | then valuenum 105 | else null end 106 | ) as fio2_chartevents 107 | FROM mimic_icu.chartevents 108 | where ITEMID = 223835 -- Inspired O2 Fraction (FiO2) 109 | and valuenum > 0 and valuenum <= 100 110 | group by subject_id, charttime 111 | ) 112 | , stg2 as 113 | ( 114 | select bg.* 115 | , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s1.charttime DESC) as lastRowSpO2 116 | , s1.spo2 117 | from bg 118 | left join stg_spo2 s1 119 | -- same hospitalization 120 | on bg.subject_id = s1.subject_id 121 | -- spo2 occurred at most 2 hours before this blood gas 122 | and s1.charttime between DATE(bg.charttime - INTERVAL '2 HOURS') and bg.charttime 123 | where bg.po2 is not null 124 | ) 125 | , stg3 as 126 | ( 127 | select bg.* 128 | , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s2.charttime DESC) as lastRowFiO2 129 | , s2.fio2_chartevents 130 | -- create our specimen prediction 131 | , 1/(1+exp(-(-0.02544 132 | + 0.04598 * po2 133 | + coalesce(-0.15356 * spo2 , -0.15356 * 97.49420 + 0.13429) 134 | + coalesce( 0.00621 * fio2_chartevents , 0.00621 * 51.49550 + -0.24958) 135 | + coalesce( 0.10559 * hemoglobin , 0.10559 * 10.32307 + 0.05954) 136 | + coalesce( 0.13251 * so2 , 0.13251 * 93.66539 + -0.23172) 137 | + coalesce(-0.01511 * pco2 , -0.01511 * 42.08866 + -0.01630) 138 | + coalesce( 0.01480 * fio2 , 0.01480 * 63.97836 + -0.31142) 139 | + coalesce(-0.00200 * aado2 , -0.00200 * 442.21186 + -0.01328) 140 | + coalesce(-0.03220 * bicarbonate , -0.03220 * 22.96894 + -0.06535) 141 | + coalesce( 0.05384 * totalco2 , 0.05384 * 24.72632 + -0.01405) 142 | + coalesce( 0.08202 * lactate , 0.08202 * 3.06436 + 0.06038) 143 | + coalesce( 0.10956 * ph , 0.10956 * 7.36233 + -0.00617) 144 | + coalesce( 0.00848 * o2flow , 0.00848 * 7.59362 + -0.35803) 145 | ))) as specimen_prob 146 | from stg2 bg 147 | left join stg_fio2 s2 148 | -- same patient 149 | on bg.subject_id = s2.subject_id 150 | -- fio2 occurred at most 4 hours before this blood gas 151 | and s2.charttime between DATE(bg.charttime - INTERVAL '4 HOURS') and bg.charttime 152 | AND s2.fio2_chartevents > 0 153 | where bg.lastRowSpO2 = 1 -- only the row with the most recent SpO2 (if no SpO2 found lastRowSpO2 = 1) 154 | ) 155 | select 156 | stg3.subject_id 157 | , stg3.hadm_id 158 | , stg3.charttime 159 | -- raw data indicating sample type 160 | , specimen 161 | -- prediction of specimen for obs missing the actual specimen 162 | , case 163 | when specimen is not null then specimen 164 | when specimen_prob > 0.75 then 'ART.' 165 | else null end as specimen_pred 166 | , specimen_prob 167 | 168 | -- oxygen related parameters 169 | , so2 170 | , po2 171 | , pco2 172 | , fio2_chartevents, fio2 173 | , aado2 174 | -- also calculate AADO2 175 | , case 176 | when po2 is null 177 | OR pco2 is null 178 | THEN NULL 179 | WHEN fio2 IS NOT NULL 180 | -- multiple by 100 because fio2 is in a % but should be a fraction 181 | THEN (fio2/100) * (760 - 47) - (pco2/0.8) - po2 182 | WHEN fio2_chartevents IS NOT NULL 183 | THEN (fio2_chartevents/100) * (760 - 47) - (pco2/0.8) - po2 184 | else null 185 | end as aado2_calc 186 | , case 187 | when PO2 is null 188 | THEN NULL 189 | WHEN fio2 IS NOT NULL 190 | -- multiply by 100 because fio2 is in a % but should be a fraction 191 | then 100 * PO2/fio2 192 | WHEN fio2_chartevents IS NOT NULL 193 | -- multiply by 100 because fio2 is in a % but should be a fraction 194 | then 100 * PO2/fio2_chartevents 195 | else null 196 | end as pao2fio2ratio 197 | -- acid-base parameters 198 | , ph, baseexcess 199 | , bicarbonate, totalco2 200 | 201 | -- blood count parameters 202 | , hematocrit 203 | , hemoglobin 204 | , carboxyhemoglobin 205 | , methemoglobin 206 | 207 | -- chemistry 208 | , chloride, calcium 209 | , temperature 210 | , potassium, sodium 211 | , lactate 212 | , glucose 213 | 214 | -- ventilation stuff that's sometimes input 215 | -- , intubated, tidalvolume, ventilationrate, ventilator 216 | -- , peep, o2flow 217 | -- , requiredo2 218 | from stg3 219 | where lastRowFiO2 = 1 -- only the most recent FiO2 220 | ; 221 | -------------------------------------------------------------------------------- /concepts_PG_local/Materialized_views/bg_pg_mv.sql: -------------------------------------------------------------------------------- 1 | -- The aim of this query is to pivot entries related to blood gases 2 | -- which were found in LABEVENTS 3 | 4 | CREATE materialized view mimiciv.bg_mv AS 5 | 6 | WITH bg AS 7 | ( 8 | select 9 | -- specimen_id only ever has 1 measurement for each itemid 10 | -- so, we may simply collapse rows using MAX() 11 | MAX(subject_id) AS subject_id 12 | , MAX(hadm_id) AS hadm_id 13 | , MAX(charttime) AS charttime 14 | -- specimen_id *may* have different storetimes, so this is taking the latest 15 | , MAX(storetime) AS storetime 16 | , le.specimen_id 17 | , MAX(CASE WHEN itemid = 52028 THEN value ELSE NULL END) AS specimen 18 | , MAX(CASE WHEN itemid = 50801 THEN valuenum ELSE NULL END) AS aado2 19 | , MAX(CASE WHEN itemid = 50802 THEN valuenum ELSE NULL END) AS baseexcess 20 | , MAX(CASE WHEN itemid = 50803 THEN valuenum ELSE NULL END) AS bicarbonate 21 | , MAX(CASE WHEN itemid = 50804 THEN valuenum ELSE NULL END) AS totalco2 22 | , MAX(CASE WHEN itemid = 50805 THEN valuenum ELSE NULL END) AS carboxyhemoglobin 23 | , MAX(CASE WHEN itemid = 50806 THEN valuenum ELSE NULL END) AS chloride 24 | , MAX(CASE WHEN itemid = 50808 THEN valuenum ELSE NULL END) AS calcium 25 | , MAX(CASE WHEN itemid = 50809 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS glucose 26 | , MAX(CASE WHEN itemid = 50810 and valuenum <= 100 THEN valuenum ELSE NULL END) AS hematocrit 27 | , MAX(CASE WHEN itemid = 50811 THEN valuenum ELSE NULL END) AS hemoglobin 28 | , MAX(CASE WHEN itemid = 50813 and valuenum <= 10000 THEN valuenum ELSE NULL END) AS lactate 29 | , MAX(CASE WHEN itemid = 50814 THEN valuenum ELSE NULL END) AS methemoglobin 30 | , MAX(CASE WHEN itemid = 50815 THEN valuenum ELSE NULL END) AS o2flow 31 | -- fix a common unit conversion error for fio2 32 | -- atmospheric o2 is 20.89%, so any value <= 20 is unphysiologic 33 | -- usually this is a misplaced O2 flow measurement 34 | , MAX(CASE WHEN itemid = 50816 THEN 35 | CASE 36 | WHEN valuenum > 20 AND valuenum <= 100 THEN valuenum 37 | WHEN valuenum > 0.2 AND valuenum <= 1.0 THEN valuenum*100.0 38 | ELSE NULL END 39 | ELSE NULL END) AS fio2 40 | , MAX(CASE WHEN itemid = 50817 AND valuenum <= 100 THEN valuenum ELSE NULL END) AS so2 41 | , MAX(CASE WHEN itemid = 50818 THEN valuenum ELSE NULL END) AS pco2 42 | , MAX(CASE WHEN itemid = 50819 THEN valuenum ELSE NULL END) AS peep 43 | , MAX(CASE WHEN itemid = 50820 THEN valuenum ELSE NULL END) AS ph 44 | , MAX(CASE WHEN itemid = 50821 THEN valuenum ELSE NULL END) AS po2 45 | , MAX(CASE WHEN itemid = 50822 THEN valuenum ELSE NULL END) AS potassium 46 | , MAX(CASE WHEN itemid = 50823 THEN valuenum ELSE NULL END) AS requiredo2 47 | , MAX(CASE WHEN itemid = 50824 THEN valuenum ELSE NULL END) AS sodium 48 | , MAX(CASE WHEN itemid = 50825 THEN valuenum ELSE NULL END) AS temperature 49 | , MAX(CASE WHEN itemid = 50807 THEN value ELSE NULL END) AS comments 50 | FROM mimic_hosp.labevents le 51 | where le.ITEMID in 52 | -- blood gases 53 | ( 54 | 52028 -- specimen 55 | , 50801 -- aado2 56 | , 50802 -- base excess 57 | , 50803 -- bicarb 58 | , 50804 -- calc tot co2 59 | , 50805 -- carboxyhgb 60 | , 50806 -- chloride 61 | -- , 52390 -- chloride, WB CL- 62 | , 50807 -- comments 63 | , 50808 -- free calcium 64 | , 50809 -- glucose 65 | , 50810 -- hct 66 | , 50811 -- hgb 67 | , 50813 -- lactate 68 | , 50814 -- methemoglobin 69 | , 50815 -- o2 flow 70 | , 50816 -- fio2 71 | , 50817 -- o2 sat 72 | , 50818 -- pco2 73 | , 50819 -- peep 74 | , 50820 -- pH 75 | , 50821 -- pO2 76 | , 50822 -- potassium 77 | -- , 52408 -- potassium, WB K+ 78 | , 50823 -- required O2 79 | , 50824 -- sodium 80 | -- , 52411 -- sodium, WB NA + 81 | , 50825 -- temperature 82 | ) 83 | GROUP BY le.specimen_id 84 | ) 85 | , stg_spo2 as 86 | ( 87 | select subject_id, charttime 88 | -- avg here is just used to group SpO2 by charttime 89 | , AVG(valuenum) as SpO2 90 | FROM mimic_icu.chartevents 91 | where ITEMID = 220277 -- O2 saturation pulseoxymetry 92 | and valuenum > 0 and valuenum <= 100 93 | group by subject_id, charttime 94 | ) 95 | , stg_fio2 as 96 | ( 97 | select subject_id, charttime 98 | -- pre-process the FiO2s to ensure they are between 21-100% 99 | , max( 100 | case 101 | when valuenum > 0.2 and valuenum <= 1 102 | then valuenum * 100 103 | -- improperly input data - looks like O2 flow in litres 104 | when valuenum > 1 and valuenum < 20 105 | then null 106 | when valuenum >= 20 and valuenum <= 100 107 | then valuenum 108 | else null end 109 | ) as fio2_chartevents 110 | FROM mimic_icu.chartevents 111 | where ITEMID = 223835 -- Inspired O2 Fraction (FiO2) 112 | and valuenum > 0 and valuenum <= 100 113 | group by subject_id, charttime 114 | ) 115 | , stg2 as 116 | ( 117 | select bg.* 118 | , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s1.charttime DESC) as lastRowSpO2 119 | , s1.spo2 120 | from bg 121 | left join stg_spo2 s1 122 | -- same hospitalization 123 | on bg.subject_id = s1.subject_id 124 | -- spo2 occurred at most 2 hours before this blood gas 125 | and s1.charttime between DATE(bg.charttime - INTERVAL '2 HOURS') and bg.charttime 126 | where bg.po2 is not null 127 | ) 128 | , stg3 as 129 | ( 130 | select bg.* 131 | , ROW_NUMBER() OVER (partition by bg.subject_id, bg.charttime order by s2.charttime DESC) as lastRowFiO2 132 | , s2.fio2_chartevents 133 | -- create our specimen prediction 134 | , 1/(1+exp(-(-0.02544 135 | + 0.04598 * po2 136 | + coalesce(-0.15356 * spo2 , -0.15356 * 97.49420 + 0.13429) 137 | + coalesce( 0.00621 * fio2_chartevents , 0.00621 * 51.49550 + -0.24958) 138 | + coalesce( 0.10559 * hemoglobin , 0.10559 * 10.32307 + 0.05954) 139 | + coalesce( 0.13251 * so2 , 0.13251 * 93.66539 + -0.23172) 140 | + coalesce(-0.01511 * pco2 , -0.01511 * 42.08866 + -0.01630) 141 | + coalesce( 0.01480 * fio2 , 0.01480 * 63.97836 + -0.31142) 142 | + coalesce(-0.00200 * aado2 , -0.00200 * 442.21186 + -0.01328) 143 | + coalesce(-0.03220 * bicarbonate , -0.03220 * 22.96894 + -0.06535) 144 | + coalesce( 0.05384 * totalco2 , 0.05384 * 24.72632 + -0.01405) 145 | + coalesce( 0.08202 * lactate , 0.08202 * 3.06436 + 0.06038) 146 | + coalesce( 0.10956 * ph , 0.10956 * 7.36233 + -0.00617) 147 | + coalesce( 0.00848 * o2flow , 0.00848 * 7.59362 + -0.35803) 148 | ))) as specimen_prob 149 | from stg2 bg 150 | left join stg_fio2 s2 151 | -- same patient 152 | on bg.subject_id = s2.subject_id 153 | -- fio2 occurred at most 4 hours before this blood gas 154 | and s2.charttime between DATE(bg.charttime - INTERVAL '4 HOURS') and bg.charttime 155 | AND s2.fio2_chartevents > 0 156 | where bg.lastRowSpO2 = 1 -- only the row with the most recent SpO2 (if no SpO2 found lastRowSpO2 = 1) 157 | ) 158 | select 159 | stg3.subject_id 160 | , stg3.hadm_id 161 | , stg3.charttime 162 | -- raw data indicating sample type 163 | , specimen 164 | -- prediction of specimen for obs missing the actual specimen 165 | , case 166 | when specimen is not null then specimen 167 | when specimen_prob > 0.75 then 'ART.' 168 | else null end as specimen_pred 169 | , specimen_prob 170 | 171 | -- oxygen related parameters 172 | , so2 173 | , po2 174 | , pco2 175 | , fio2_chartevents, fio2 176 | , aado2 177 | -- also calculate AADO2 178 | , case 179 | when po2 is null 180 | OR pco2 is null 181 | THEN NULL 182 | WHEN fio2 IS NOT NULL 183 | -- multiple by 100 because fio2 is in a % but should be a fraction 184 | THEN (fio2/100) * (760 - 47) - (pco2/0.8) - po2 185 | WHEN fio2_chartevents IS NOT NULL 186 | THEN (fio2_chartevents/100) * (760 - 47) - (pco2/0.8) - po2 187 | else null 188 | end as aado2_calc 189 | , case 190 | when PO2 is null 191 | THEN NULL 192 | WHEN fio2 IS NOT NULL 193 | -- multiply by 100 because fio2 is in a % but should be a fraction 194 | then 100 * PO2/fio2 195 | WHEN fio2_chartevents IS NOT NULL 196 | -- multiply by 100 because fio2 is in a % but should be a fraction 197 | then 100 * PO2/fio2_chartevents 198 | else null 199 | end as pao2fio2ratio 200 | -- acid-base parameters 201 | , ph, baseexcess 202 | , bicarbonate, totalco2 203 | 204 | -- blood count parameters 205 | , hematocrit 206 | , hemoglobin 207 | , carboxyhemoglobin 208 | , methemoglobin 209 | 210 | -- chemistry 211 | , chloride, calcium 212 | , temperature 213 | , potassium, sodium 214 | , lactate 215 | , glucose 216 | 217 | -- ventilation stuff that's sometimes input 218 | -- , intubated, tidalvolume, ventilationrate, ventilator 219 | -- , peep, o2flow 220 | -- , requiredo2 221 | from stg3 222 | where lastRowFiO2 = 1 -- only the most recent FiO2 223 | ; 224 | --------------------------------------------------------------------------------