#' add materialized view data for mimic III
#'
#' @param ccs_multi_dx ccs_multi_dx.csv.gz or ccs_multi_dx.csv file path with file name
#' @param conn connection of MIMIC, if missing, it well be got from global environment by connect_MIMIC
#'
#' @return 94 materialized view data
#' @export
#'
#' @examples
#' \donttest{
#' addMatView_3("F:/ccs_multi_dx.csv.gz")
#' }
addMatView_3 <- function(ccs_multi_dx,conn){
# use
# 2 top level data ----
code_status <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS code_status;\nCREATE MATERIALIZED VIEW mimic3.code_status\nTABLESPACE pg_default\nAS\n-- jing add head\n-- This query extracts:\n-- i) a patient's first code status\n-- ii) a patient's last code status\n-- iii) the time of the first entry of DNR or CMO\n\nwith t1 as\n(\n select icustay_id, charttime, value\n -- use row number to identify first and last code status\n , ROW_NUMBER() over (PARTITION BY icustay_id order by charttime) as rnfirst\n , ROW_NUMBER() over (PARTITION BY icustay_id order by charttime desc) as rnlast\n\n -- coalesce the values\n , case\n when value in ('Full Code','Full code') then 1\n else 0 end as fullcode\n , case\n when value in ('Comfort Measures','Comfort measures only') then 1\n else 0 end as cmo\n , case\n when value = 'CPR Not Indicate' then 1\n else 0 end as dncpr -- only in CareVue, i.e. only possible for ~60-70% of patients\n , case\n when value in ('Do Not Intubate','DNI (do not intubate)','DNR / DNI') then 1\n else 0 end as dni\n , case\n when value in ('Do Not Resuscita','DNR (do not resuscitate)','DNR / DNI') then 1\n else 0 end as dnr\n FROM chartevents\n where itemid in (128, 223758)\n and value is not null\n and value != 'Other/Remarks'\n -- exclude rows marked as error\n AND (error IS NULL OR error = 0)\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n -- first recorded code status\n , max(case when rnfirst = 1 then t1.fullcode else null end) as fullcode_first\n , max(case when rnfirst = 1 then t1.cmo else null end) as cmo_first\n , max(case when rnfirst = 1 then t1.dnr else null end) as dnr_first\n , max(case when rnfirst = 1 then t1.dni else null end) as dni_first\n , max(case when rnfirst = 1 then t1.dncpr else null end) as dncpr_first\n\n -- last recorded code status\n , max(case when rnlast = 1 then t1.fullcode else null end) as fullcode_last\n , max(case when rnlast = 1 then t1.cmo else null end) as cmo_last\n , max(case when rnlast = 1 then t1.dnr else null end) as dnr_last\n , max(case when rnlast = 1 then t1.dni else null end) as dni_last\n , max(case when rnlast = 1 then t1.dncpr else null end) as DNCPR_last\n\n -- were they *at any time* given a certain code status\n , max(t1.fullcode) as fullcode\n , max(t1.cmo) as cmo\n , max(t1.dnr) as dnr\n , max(t1.dni) as dni\n , max(t1.dncpr) as dncpr\n\n -- time until their first DNR\n , min(case when t1.dnr = 1 then t1.charttime else null end)\n as dnr_first_charttime\n , min(case when t1.dni = 1 then t1.charttime else null end)\n as dni_first_charttime\n , min(case when t1.dncpr = 1 then t1.charttime else null end)\n as dncpr_first_charttime\n\n -- first code status of CMO\n , min(case when t1.cmo = 1 then t1.charttime else null end)\n as timecmo_chart\n\nFROM icustays ie\nleft join t1\n on ie.icustay_id = t1.icustay_id\ngroup by ie.subject_id, ie.hadm_id, ie.icustay_id, ie.intime;\n-- jing add tail\nALTER TABLE mimic3.code_status\nOWNER TO postgres;"
echo_data <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS echo_data;\ncreate materialized view mimic3.echo_data\ntablespace pg_default\nas\n-- jing add head\n-- This code extracts structured data from echocardiographies\n-- You can join it to the text notes using ROW_ID\n-- Just note that ROW_ID will differ across versions of MIMIC-III.\n\nselect ROW_ID\n , subject_id, hadm_id\n , chartdate\n\n -- charttime is always null for echoes..\n -- however, the time is available in the echo text, e.g.:\n -- , substring(ne.text, 'Date/Time: [\\[\\]0-9*-]+ at ([0-9:]+)') as TIMESTAMP\n -- we can therefore impute it and re-create charttime\n , PARSE_DATETIME\n (\n '%Y-%m-%d%H:%M:%S',\n FORMAT_DATE('%Y-%m-%d', chartdate)\n || REGEXP_EXTRACT(ne.text, 'Date/Time: .+? at ([0-9]+:[0-9]{2})')\n || ':00'\n ) AS charttime\n\n -- explanation of below substring:\n -- 'Indication: ' - matched verbatim\n -- (.*?) - match any character\n -- \\n - the end of the line\n -- substring only returns the item in ()s\n -- note: the '?' makes it non-greedy. if you exclude it, it matches until it reaches the *last* \\n\n\n , REGEXP_EXTRACT(ne.text, 'Indication: (.*?)\\n') as Indication\n\n -- sometimes numeric values contain de-id text, e.g. [** Numeric Identifier **]\n -- this removes that text\n , cast(REGEXP_EXTRACT(ne.text, 'Height[(: ]{0,}in[): ]{0,}([0-9\\.]+)') as numeric) as height\n , cast(REGEXP_EXTRACT(ne.text, 'Weight[(: ]{0,}lb[): ]{0,}([0-9\\.]+)\\n') as numeric) as Weight\n , cast(REGEXP_EXTRACT(ne.text, 'BSA[(: ]{0,}m2[): ]{0,}([0-9\\.]+) m2\\n') as numeric) as BSA -- ends in 'm2'\n , REGEXP_EXTRACT(ne.text, 'BP[(: ]{0,}mm Hg[): ]{0,}(.+)\\n') as BP -- Sys/Dias\n , cast(REGEXP_EXTRACT(ne.text, 'BP[(: ]{0,}mm Hg[): ]{0,}([0-9\\.]+)/[0-9\\.]+?\\n') as numeric) as BPSys -- first part of fraction\n , cast(REGEXP_EXTRACT(ne.text, 'BP[(: ]{0,}mm Hg[): ]{0,}[0-9\\.]+/([0-9\\.]+?)\\n') as numeric) as BPDias -- second part of fraction\n , cast(REGEXP_EXTRACT(ne.text, 'HR[(: ]{0,}bpm[): ]{0,}([0-9\\.]+?)\\n') as numeric) as HR\n\n , REGEXP_EXTRACT(ne.text, 'Status: (.*?)\\n') as Status\n , REGEXP_EXTRACT(ne.text, 'Test: (.*?)\\n') as Test\n , REGEXP_EXTRACT(ne.text, 'Doppler: (.*?)\\n') as Doppler\n , REGEXP_EXTRACT(ne.text, 'Contrast: (.*?)\\n') as Contrast\n , REGEXP_EXTRACT(ne.text, 'Technical Quality: (.*?)\\n') as TechnicalQuality\nFROM noteevents ne\nwhere category = 'Echo';\n-- jing add tail\nalter table mimic3.echo_data\nowner to postgres;"
# 23 durations------
ventilation_classification <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_ventilation_classification;\nCREATE MATERIALIZED VIEW mimic3.durations_ventilation_classification\nTABLESPACE pg_default\nAS\n-- jing add head\n-- Identify The presence of a mechanical ventilation using settings\nselect\n icustay_id, charttime\n -- case statement determining whether it is an instance of mech vent\n , max(\n case\n when itemid is null or value is null then 0 -- can't have null values\n when itemid = 720 and value != 'Other/Remarks' THEN 1 -- VentTypeRecorded\n when itemid = 223848 and value != 'Other' THEN 1\n when itemid = 223849 then 1 -- ventilator mode\n when itemid = 467 and value = 'Ventilator' THEN 1 -- O2 delivery device == ventilator\n when itemid in\n (\n 445, 448, 449, 450, 1340, 1486, 1600, 224687 -- minute volume\n , 639, 654, 681, 682, 683, 684,224685,224684,224686 -- tidal volume\n , 218,436,535,444,459,224697,224695,224696,224746,224747 -- High/Low/Peak/Mean/Neg insp force (\"RespPressure\")\n , 221,1,1211,1655,2000,226873,224738,224419,224750,227187 -- Insp pressure\n , 543 -- PlateauPressure\n , 5865,5866,224707,224709,224705,224706 -- APRV pressure\n , 60,437,505,506,686,220339,224700 -- PEEP\n , 3459 -- high pressure relief\n , 501,502,503,224702 -- PCV\n , 223,667,668,669,670,671,672 -- TCPCV\n , 224701 -- PSVlevel\n )\n THEN 1\n else 0\n end\n ) as MechVent\n , max(\n case\n -- initiation of oxygen therapy indicates the ventilation has ended\n when itemid = 226732 and value in\n (\n 'Nasal cannula', -- 153714 observations\n 'Face tent', -- 24601 observations\n 'Aerosol-cool', -- 24560 observations\n 'Trach mask ', -- 16435 observations\n 'High flow neb', -- 10785 observations\n 'Non-rebreather', -- 5182 observations\n 'Venti mask ', -- 1947 observations\n 'Medium conc mask ', -- 1888 observations\n 'T-piece', -- 1135 observations\n 'High flow nasal cannula', -- 925 observations\n 'Ultrasonic neb', -- 9 observations\n 'Vapomist' -- 3 observations\n ) then 1\n when itemid = 467 and value in\n (\n 'Cannula', -- 278252 observations\n 'Nasal Cannula', -- 248299 observations\n -- 'None', -- 95498 observations\n 'Face Tent', -- 35766 observations\n 'Aerosol-Cool', -- 33919 observations\n 'Trach Mask', -- 32655 observations\n 'Hi Flow Neb', -- 14070 observations\n 'Non-Rebreather', -- 10856 observations\n 'Venti Mask', -- 4279 observations\n 'Medium Conc Mask', -- 2114 observations\n 'Vapotherm', -- 1655 observations\n 'T-Piece', -- 779 observations\n 'Hood', -- 670 observations\n 'Hut', -- 150 observations\n 'TranstrachealCat', -- 78 observations\n 'Heated Neb', -- 37 observations\n 'Ultrasonic Neb' -- 2 observations\n ) then 1\n else 0\n end\n ) as OxygenTherapy\n , max(\n case when itemid is null or value is null then 0\n -- extubated indicates ventilation event has ended\n when itemid = 640 and value = 'Extubated' then 1\n when itemid = 640 and value = 'Self Extubation' then 1\n else 0\n end\n )\n as Extubated\n , max(\n case when itemid is null or value is null then 0\n when itemid = 640 and value = 'Self Extubation' then 1\n else 0\n
end\n )\n as SelfExtubated\nfrom chartevents ce\nwhere ce.value is not null\n-- exclude rows marked as error\nand (ce.error != 1 or ce.error IS NULL)\nand itemid in\n(\n -- the below are settings used to indicate ventilation\n 720, 223849 -- vent mode\n , 223848 -- vent type\n , 445, 448, 449, 450, 1340, 1486, 1600, 224687 -- minute volume\n , 639, 654, 681, 682, 683, 684,224685,224684,224686 -- tidal volume\n , 218,436,535,444,224697,224695,224696,224746,224747 -- High/Low/Peak/Mean (\"RespPressure\")\n , 221,1,1211,1655,2000,226873,224738,224419,224750,227187 -- Insp pressure\n , 543 -- PlateauPressure\n , 5865,5866,224707,224709,224705,224706 -- APRV pressure\n , 60,437,505,506,686,220339,224700 -- PEEP\n , 3459 -- high pressure relief\n , 501,502,503,224702 -- PCV\n , 223,667,668,669,670,671,672 -- TCPCV\n , 224701 -- PSVlevel\n\n -- the below are settings used to indicate extubation\n , 640 -- extubated\n\n -- the below indicate oxygen/NIV, i.e. the end of a mechanical vent event\n , 468 -- O2 Delivery Device#2\n , 469 -- O2 Delivery Mode\n , 470 -- O2 Flow (lpm)\n , 471 -- O2 Flow (lpm) #2\n , 227287 -- O2 Flow (additional cannula)\n , 226732 -- O2 Delivery Device(s)\n , 223834 -- O2 Flow\n\n -- used in both oxygen + vent calculation\n , 467 -- O2 Delivery Device\n)\ngroup by icustay_id, charttime\nUNION DISTINCT\n-- add in the extubation flags from procedureevents_mv\n-- note that we only need the start time for the extubation\n-- (extubation is always charted as ending 1 minute after it started)\nselect\n icustay_id, starttime as charttime\n , 0 as MechVent\n , 0 as OxygenTherapy\n , 1 as Extubated\n , case when itemid = 225468 then 1 else 0 end as SelfExtubated\nfrom procedureevents_mv\nwhere itemid in\n(\n 227194 -- \"Extubation\"\n, 225468 -- \"Unplanned Extubation (patient-initiated)\"\n, 225477 -- \"Unplanned Extubation (non-patient initiated)\"\n);\n-- jing add tail\nALTER TABLE mimic3.durations_ventilation_classification\nOWNER TO postgres;"
ventilation_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_ventilation_durations;\nCREATE MATERIALIZED VIEW mimic3.durations_ventilation_durations\nTABLESPACE pg_default\nAS\n-- jing add head\n-- this query extracts the duration of mechanical ventilation\n-- the main goal of the query is to aggregate sequential ventilator settings\n-- into single mechanical ventilation \"events\". the start and end time of these\n-- events can then be used for various purposes: calculating the total duration\n-- of mechanical ventilation, cross-checking values (e.g. pao2:fio2 on vent), etc\n\n-- the query's logic is roughly:\n-- 1) the presence of a mechanical ventilation setting starts a new ventilation event\n-- 2) any instance of a setting in the next 8 hours continues the event\n-- 3) certain elements end the current ventilation event\n-- a) documented extubation ends the current ventilation\n-- b) initiation of non-invasive vent and/or oxygen ends the current vent\n\n-- see the ventilation_classification.sql query for step 1 of the above.\n-- this query has the logic for converting events into durations.\nwith vd0 as\n(\n select\n icustay_id\n -- this carries over the previous charttime which had a mechanical ventilation event\n , case\n when mechvent=1 then\n lag(charttime, 1) over (partition by icustay_id, mechvent order by charttime)\n else null\n end as charttime_lag\n , charttime\n , mechvent\n , oxygentherapy\n , extubated\n , selfextubated\n from durations_ventilation_classification\n)\n, vd1 as\n(\n select\n icustay_id\n , charttime_lag\n , charttime\n , mechvent\n , oxygentherapy\n , extubated\n , selfextubated\n\n -- if this is a mechanical ventilation event, we calculate the time since the last event\n , case\n -- if the current observation indicates mechanical ventilation is present\n -- calculate the time since the last vent event\n when mechvent=1 then\n datetime_diff(charttime, charttime_lag,'MINUTE')/60\n else null\n end as ventduration\n\n , lag(extubated,1)\n over\n (\n partition by icustay_id, case when mechvent=1 or extubated=1 then 1 else 0 end\n order by charttime\n ) as extubatedlag\n\n -- now we determine if the current mech vent event is a \"new\", i.e. they've just been intubated\n , case\n -- if there is an extubation flag, we mark any subsequent ventilation as a new ventilation event\n
--when extubated = 1 then 0 -- extubation is *not* a new ventilation event, the *subsequent* row is\n when\n lag(extubated,1)\n over\n (\n partition by icustay_id, case when mechvent=1 or extubated=1 then 1 else 0 end\n order by charttime\n )\n = 1 then 1\n -- if patient has initiated oxygen therapy, and is not currently vented, start a newvent\n when mechvent = 0 and oxygentherapy = 1 then 1\n -- if there is less than 8 hours between vent settings, we do not treat this as a new ventilation event\n when charttime > datetime_add(charttime_lag, interval '8' hour)\n then 1\n else 0\n end as newvent\n -- use the staging table with only vent settings from chart events\n from vd0 ventsettings\n)\n, vd2 as\n(\n select vd1.*\n -- create a cumulative sum of the instances of new ventilation\n -- this results in a monotonic integer assigned to each instance of ventilation\n , case when mechvent=1 or extubated = 1 then\n sum( newvent )\n over ( partition by icustay_id order by charttime )\n else null end\n as ventnum\n --- now we convert charttime of ventilator settings into durations\n from vd1\n)\n-- create the durations for each mechanical ventilation instance\nselect icustay_id\n -- regenerate ventnum so it's sequential\n , row_number() over (partition by icustay_id order by ventnum) as ventnum\n , min(charttime) as starttime\n , max(charttime) as endtime\n , datetime_diff(max(charttime), min(charttime),'MINUTE')/60 as duration_hours\nfrom vd2\ngroup by icustay_id, vd2.ventnum\nhaving min(charttime) != max(charttime)\n-- patient had to be mechanically ventilated at least once\n-- i.e. max(mechvent) should be 1\n-- this excludes a frequent situation of niv/oxygen before intub\n-- in these cases, ventnum=0 and max(mechvent)=0, so they are ignored\nand max(mechvent) = 1\norder by icustay_id, ventnum;\n-- jing add tail\nALTER TABLE mimic3.durations_ventilation_durations\nOWNER TO postgres;"
crrt_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_crrt_durations;\nCREATE MATERIALIZED VIEW mimic3.durations_crrt_durations\nTABLESPACE pg_default\nAS\n-- jing add head\nwith crrt_settings as\n(\n select ce.icustay_id, ce.charttime\n , max(\n case\n when ce.itemid in\n (\n 224149, -- access pressure\n 224144, -- blood flow (ml/min)\n 228004, -- citrate (acd-a)\n 225183, -- current goal\n 225977, -- dialysate fluid\n 224154, -- dialysate rate\n 224151, -- effluent pressure\n 224150, -- filter pressure\n 225958, -- heparin concentration (units/ml)\n 224145, -- heparin dose (per hour)\n 224191, -- hourly patient fluid removal\n 228005, -- pbp (prefilter) replacement rate\n 228006, -- post filter replacement rate\n 225976, -- replacement fluid\n 224153, -- replacement rate\n 224152, -- return pressure\n 226457 -- ultrafiltrate output\n ) then 1\n when ce.itemid in\n (\n 29, -- access mmhg\n 173, -- effluent press mmhg\n 192, -- filter pressure mmhg\n 624, -- return pressure mmhg\n 79, -- blood flow ml/min\n 142, -- current goal\n 146, -- dialysate flow ml/hr\n 611, -- replace rate ml/hr\n 5683 -- hourly pfr\n ) then 1\n when ce.itemid = 665 and value in ('active','clot increasing','clots present','no clot present')\n then 1\n when ce.itemid = 147 and value = 'yes'\n then 1\n else 0 end)\n as rrt\n -- below indicates that a new instance of crrt has started\n , max(\n case\n -- system integrity\n when ce.itemid = 224146 and value in ('new filter','reinitiated')\n then 1\n when ce.itemid = 665 and value in ('initiated')\n then 1\n else 0\n end ) as rrt_start\n -- below indicates that the current instance of crrt has ended\n , max(\n case\n -- system integrity\n when ce.itemid = 224146 and value in ('discontinued','recirculating')\n then 1\n -- the only value like dc is \"dc'd\", use like to avoid apostrophe\n when ce.itemid = 665 and (value = 'clotted' or value like 'dc%')\n then 1\n -- reason for crrt filter change\n when ce.itemid = 225956\n then 1\n else 0\n end ) as rrt_end\n from chartevents ce\n where ce.itemid in\n (\n -- metavision itemids\n -- below require special handling\n 224146, -- system integrity\n 225956, -- reason for crrt filter change\n -- below are settings which indicate crrt is started/continuing\n 224149, -- access pressure\n 224144, -- blood flow (ml/min)\n 228004, -- citrate (acd-a)\n 225183, -- current goal\n 225977, -- dialysate fluid\n 224154, -- dialysate rate\n 224151, -- effluent pressure\n 224150, -- filter pressure\n 225958, -- heparin concentration (units/ml)\n 224145, -- heparin dose (per hour)\n 224191, -- hourly patient fluid removal\n 228005, -- pbp (prefilter) replacement rate\n 228006, -- post filter replacement rate\n 225976, -- replacement fluid\n 224153, -- replacement rate\n 224152, -- return pressure\n
226457, -- ultrafiltrate output\n -- carevue itemids\n -- below require special handling\n 665, -- system integrity\n 147, -- dialysate infusing\n 612, -- replace.fluid infuse\n -- below are settings which indicate crrt is started/continuing\n 29, -- access mmhg\n 173, -- effluent press mmhg\n 192, -- filter pressure mmhg\n 624, -- return pressure mmhg\n 142, -- current goal\n 79, -- blood flow ml/min\n 146, -- dialysate flow ml/hr\n 611, -- replace rate ml/hr\n 5683 -- hourly pfr\n )\n and ce.value is not null\n and coalesce(ce.valuenum,1) != 0 -- non-zero rates/values\n group by icustay_id, charttime\n)\n-- create various lagged variables for future query\n, vd_lag as\n(\n select\n icustay_id\n -- this carries over the previous charttime\n , lag(charttime, 1) over w as charttime_prev_row\n , charttime\n , rrt\n , rrt_start\n , rrt_end\n , lag(rrt_end, 1) over w as rrt_ended_prev_row\n from crrt_settings\n window w as \n (\n partition by icustay_id, case when rrt=1 or rrt_end=1 then 1 else 0 end\n order by charttime\n )\n)\n, vd1 as\n(\n select\n icustay_id\n , charttime\n , rrt\n , rrt_start\n , rrt_end\n\n -- now we determine if the current event is a new instantiation\n , case\n when rrt_start = 1\n then 1\n -- if there is an end flag, we mark any subsequent event as new\n when rrt_end = 1\n -- note the end is *not* a new event, the *subsequent* row is\n -- so here we output 0\n then 0\n when rrt_ended_prev_row = 1\n then 1\n -- if there is less than 2 hours between crrt settings, we do not treat this as a new crrt event\n when datetime_diff(charttime, charttime_prev_row,'HOUR') <= 2\n then 0\n else 1\n end as newcrrt\n -- use the temp table with only settings from chartevents\n from vd_lag\n)\n, vd2 as\n(\n select vd1.*\n -- create a cumulative sum of the instances of new crrt\n -- this results in a monotonically increasing integer assigned to each crrt\n , case when rrt_start = 1 or rrt=1 or rrt_end = 1 then\n sum( newcrrt )\n over ( partition by icustay_id order by charttime )\n else null end\n as num\n --- now we convert charttime of crrt settings into durations\n from vd1\n -- now we can isolate to just rows with settings\n -- (before we had rows with start/end flags)\n -- this removes any null values for newcrrt\n where\n rrt_start = 1 or rrt = 1 or rrt_end = 1\n)\n-- create the durations for each crrt instance\n, fin as\n(\nselect icustay_id\n , num\n , min(charttime) as starttime\n , max(charttime) as endtime\n \t, datetime_diff(max(charttime), min(charttime),'HOUR') as duration_hours\n -- add durations\nfrom vd2\ngroup by icustay_id, num\nhaving min(charttime) != max(charttime)\n)\nselect icustay_id\n , row_number() over (partition by icustay_id order by starttime) as num\n , starttime, endtime, duration_hours\nfrom fin\norder by icustay_id, num;\n-- jing add tail\nALTER TABLE mimic3.durations_crrt_durations\nOWNER TO postgres;"
adenosine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_adenosine_durations; \nCREATE MATERIALIZED VIEW mimic3.durations_adenosine_durations \nTABLESPACE pg_default \nAS \n-- jing add head \n-- this query extracts durations of adenosine administration \n-- consecutive administrations are numbered 1, 2, ... \n-- Total time on the drug can be calculated from this table by grouping using icustay_id \n \n-- *** could not find adenosine in the inputevents_mv table *** \n-- this drug is rarely used - it could just be that it was never used in metavision. \n-- if using this code, ensure the durations make sense for carevue patients first \n\nwith vasocv1 as \n( \n select \n icustay_id, charttime \n -- case statement determining whether the itemid is an instance of vasopressor usage \n , max(case when itemid = 4649 then 1 else 0 end) as vaso -- adenosine \n \n -- the 'stopped' column indicates if a vasopressor has been disconnected \n , 0 as vaso_stopped \n , max(case when itemid = 4649 and valuenum is not null then 1 else 0 end) as vaso_null \n , max(case when itemid = 4649 then valuenum else null end) as vaso_rate \n , max(case when itemid = 4649 then valuenum else null end) as vaso_amount \n \n from chartevents \n where itemid = 4649 -- adenosine \n -- exclude rows marked as error \n and (error is null or error = 0) \n group by icustay_id, charttime \n) \n, vasocv2 as \n( \n select v.* \n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition \n from \n vasocv1 v \n) \n, vasocv3 as \n( \n select v.* \n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull \n from \n vasocv2 v \n) \n, vasocv4 as \n( \nselect \n icustay_id \n , charttime \n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta \n \n , vaso \n , vaso_rate \n , vaso_amount \n , vaso_stopped \n , vaso_prevrate_ifnull \n \n -- we define start time here \n , case \n when vaso = 0 then null \n \n -- if this is the first instance of the vasoactive drug \n when vaso_rate > 0 and \n lag(vaso_prevrate_ifnull,1) \n over \n ( \n
partition by icustay_id, vaso, vaso_null \n order by charttime \n ) \n is null \n then 1 \n \n -- you often get a string of 0s \n -- we decide not to set these as 1, just because it makes vasonum sequential \n when vaso_rate = 0 and \n lag(vaso_prevrate_ifnull,1) \n over \n ( \n partition by icustay_id, vaso \n order by charttime \n ) \n = 0 \n then 0 \n \n -- sometimes you get a string of null, associated with 0 volumes \n -- same reason as before, we decide not to set these as 1 \n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null \n when vaso_prevrate_ifnull = 0 and \n lag(vaso_prevrate_ifnull,1) \n over \n ( \n partition by icustay_id, vaso \n order by charttime \n ) \n = 0 \n then 0 \n \n -- if the last recorded rate was 0, newvaso = 1 \n when lag(vaso_prevrate_ifnull,1) \n over \n ( \n partition by icustay_id, vaso \n order by charttime \n ) = 0 \n then 1 \n \n -- if the last recorded vaso was d/c'd, newvaso = 1 \n when \n lag(vaso_stopped,1) \n over \n ( \n partition by icustay_id, vaso \n order by charttime \n ) \n = 1 then 1 \n \n -- ** not sure if the below is needed \n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1 \n else null \n end as vaso_start \n \nfrom \n vasocv3 \n) \n-- propagate start/stop flags forward in time \n, vasocv5 as \n( \n select v.* \n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first \nfrom \n vasocv4 v \n) \n, vasocv6 as \n( \n select v.* \n -- we define end time here \n , case \n when vaso = 0 \n then null \n \n -- if the recorded vaso was d/c'd, this is an end time \n when vaso_stopped = 1 \n then vaso_first \n \n -- if the rate is zero, this is the end time \n when vaso_rate = 0 \n then vaso_first \n \n -- the last row in the table is always a potential end time \n -- this captures patients who die/are discharged while on vasopressors \n -- in principle, this could add an extra end time for the vasopressor \n
-- however, since we later group on vaso_start, any extra end times are ignored \n when lead(charttime,1) \n over \n ( \n partition by icustay_id, vaso \n order by charttime \n ) is null \n then vaso_first \n \n else null \n end as vaso_stop \n from vasocv5 v \n) \n \n-- -- if you want to look at the results of the table before grouping: \n-- select \n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount \n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped \n-- , vaso_start \n-- , vaso_first \n-- , vaso_stop \n-- from vasocv6 order by charttime; \n \n \n, vasocv as \n( \n-- below groups together vasopressor administrations into groups \nselect \n icustay_id \n -- the first non-null rate is considered the starttime \n , min(case when vaso_rate is not null then charttime else null end) as starttime \n -- the *first* time the first/last flags agree is the stop time for this duration \n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime \nfrom vasocv6 \nwhere \n vaso_first is not null -- bogus data \nand \n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered \nand \n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these \ngroup by icustay_id, vaso_first \nhaving -- ensure start time is not the same as end time \n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end) \nand \n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery \n) \n \n-- now we extract the associated data for metavision patients \n, vasomv as \n( \n select \n icustay_id, linkorderid \n , min(starttime) as starttime, max(endtime) as endtime \n from inputevents_mv \n where itemid = 221282 -- adenosine \n and statusdescription != 'rewritten' -- only valid orders \n group by icustay_id, linkorderid \n) \n \nselect \n icustay_id \n -- generate a sequential integer for convenience \n , row_number() over (partition by icustay_id order by starttime) as vasonum \n , starttime, endtime \n , datetime_diff(endtime, starttime,'HOUR') as duration_hours \n -- add durations \nfrom \n vasocv \n \nunion all \n \nselect \n icustay_id \n , row_number() over (partition by icustay_id order by starttime) as vasonum \n , starttime, endtime \n , datetime_diff(endtime, starttime,'HOUR') as duration_hours \n -- add durations \nfrom \n vasomv \n \norder by icustay_id, vasonum; \n-- jing add tail \nALTER TABLE mimic3.durations_adenosine_durations \nOWNER TO postgres;"
dobutamine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_dobutamine_durations;\nCREATE MATERIALIZED VIEW mimic3.durations_dobutamine_durations\nTABLESPACE pg_default\nAS\n-- jing add head\n-- this query extracts durations of dobutamine administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30042,30306) then 1 else 0 end) as vaso -- dobutamine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30042,30306) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30042,30306) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30042,30306) then rate else null end) as vaso_rate\n , max(case when itemid in (30042,30306) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in (30042,30306) -- dobutamine\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n
when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n
-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221653 -- dobutamine\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nALTER TABLE mimic3.durations_dobutamine_durations\nOWNER TO postgres;"
dopamine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_dopamine_durations;\ncreate materialized view mimic3.durations_dopamine_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of dopamine administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30043,30307) then 1 else 0 end) as vaso -- dopamine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30043,30307) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30043,30307) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30043,30307) then rate else null end) as vaso_rate\n , max(case when itemid in (30043,30307) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in\n (\n 30043,30307 -- dopamine\n )\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n
lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\n
where\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221662 -- dopamine\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_dopamine_durations\nowner to postgres;"
epinephrine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_epinephrine_durations;\ncreate materialized view mimic3.durations_epinephrine_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of epinephrine administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30044,30119,30309) then 1 else 0 end) as vaso -- epinephrine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30044,30119,30309) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30044,30119,30309) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30044,30119,30309) then rate else null end) as vaso_rate\n , max(case when itemid in (30044,30119,30309) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in\n (\n 30044,30119,30309 -- epinephrine\n )\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n
-- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221289 -- epinephrine\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n
, datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_epinephrine_durations\nowner to postgres;"
isuprel_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_isuprel_durations;\ncreate materialized view mimic3.durations_isuprel_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of isuprel administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid = 30046 then 1 else 0 end) as vaso -- isuprel\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid = 30046 and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid = 30046 and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid = 30046 then rate else null end) as vaso_rate\n , max(case when itemid = 30046 then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid = 30046 -- isuprel\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n
partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 227692 -- isuprel\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n
, row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_isuprel_durations\nowner to postgres;"
milrinone_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_milrinone_durations;\ncreate materialized view mimic3.durations_milrinone_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of milrinone administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid = 30125 then 1 else 0 end) as vaso -- milrinone\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid = 30125 and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid = 30125 and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid = 30125 then rate else null end) as vaso_rate\n , max(case when itemid = 30125 then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid = 30125 -- milrinone\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n
partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221986 -- milrinone\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n
, starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_milrinone_durations\nowner to postgres;"
norepinephrine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_norepinephrine_durations;\ncreate materialized view mimic3.durations_norepinephrine_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of norepinephrine administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30047,30120) then 1 else 0 end) as vaso -- norepinephrine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30047,30120) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30047,30120) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30047,30120) then rate else null end) as vaso_rate\n , max(case when itemid in (30047,30120) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in (30047,30120) -- norepinephrine\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n
partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the carevue data before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221906 -- norepinephrine\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n
, datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_norepinephrine_durations\nowner to postgres;"
phenylephrine_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_phenylephrine_durations;\ncreate materialized view mimic3.durations_phenylephrine_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of phenylephrine administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30127,30128) then 1 else 0 end) as vaso -- phenylephrine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30127,30128) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30127,30128) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30127,30128) then rate else null end) as vaso_rate\n , max(case when itemid in (30127,30128) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in\n (\n 30127,30128 -- phenylephrine\n )\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n
partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 221749 -- phenylephrine\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n
, datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_phenylephrine_durations\nowner to postgres;"
vasopressin_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_vasopressin_durations;\ncreate materialized view mimic3.durations_vasopressin_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of vasopressin administration\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid = 30051 then 1 else 0 end) as vaso -- vasopressin\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid = 30051 and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid = 30051 and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid = 30051 then rate else null end) as vaso_rate\n , max(case when itemid = 30051 then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid = 30051 -- vasopressin\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n
= 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\ngroup by icustay_id, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from inputevents_mv\n where itemid = 222315 -- vasopressin\n and statusdescription != 'rewritten' -- only valid orders\n group by icustay_id, linkorderid\n)\n\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n
vasomv\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_vasopressin_durations\nowner to postgres;"
vasopressor_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_vasopressor_durations;\ncreate materialized view mimic3.durations_vasopressor_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts durations of vasopressor administration\n-- it groups together any administration of the below list of drugs:\n-- norepinephrine - 30047,30120,221906\n-- epinephrine - 30044,30119,30309,221289\n-- phenylephrine - 30127,30128,221749\n-- vasopressin - 30051,222315 (42273, 42802 also for 2 patients)\n-- dopamine - 30043,30307,221662\n-- dobutamine - 30042,30306,221653\n-- milrinone - 30125,221986\n\n-- consecutive administrations are numbered 1, 2, ...\n-- Total time on the drug can be calculated from this table\n-- by grouping using icustay_id\n\n-- select only the itemids from the inputevents_cv table related to vasopressors\nwith io_cv as\n(\n select\n icustay_id, charttime, itemid, stopped\n -- itemids (42273, 42802) accidentally store rate in amount column\n , case\n when itemid in (42273, 42802)\n then amount\n else rate\n end as rate\n , case\n when itemid in (42273, 42802)\n then rate\n else amount\n end as amount\n from inputevents_cv\n where itemid in\n (\n 30047,30120,30044,30119,30309,30127\n , 30128,30051,30043,30307,30042,30306,30125\n , 42273, 42802\n )\n)\n-- select only the itemids from the inputevents_mv table related to vasopressors\n, io_mv as\n(\n select\n icustay_id, linkorderid, starttime, endtime\n from inputevents_mv io\n -- subselect the vasopressor itemids\n where itemid in\n (\n 221906,221289,221749,222315,221662,221653,221986\n )\n and statusdescription != 'rewritten' -- only valid orders\n)\n, vasocv1 as\n(\n select\n icustay_id, charttime, itemid\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , 1 as vaso\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when rate is not null then 1 else 0 end) as vaso_null\n , max(rate) as vaso_rate\n , max(amount) as vaso_amount\n\n from io_cv\n group by icustay_id, charttime, itemid\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id, itemid order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, itemid, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n , itemid\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, itemid, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n
lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, itemid, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, itemid, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, itemid, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, itemid, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, itemid, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, itemid, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , case when vaso_stopped = 1 then 'y' else '' end as stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by charttime;\n\n\n, vasocv as\n(\n-- below groups together vasopressor administrations into groups\nselect\n icustay_id\n , itemid\n -- the first non-null rate is considered the starttime\n , min(case when vaso_rate is not null then charttime else null end) as starttime\n -- the *first* time the first/last flags agree is the stop time for this duration\n , min(case when vaso_first = vaso_stop then charttime else null end) as endtime\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n
group by icustay_id, itemid, vaso_first\nhaving -- ensure start time is not the same as end time\n min(charttime) != min(case when vaso_first = vaso_stop then charttime else null end)\nand\n max(vaso_rate) > 0 -- if the rate was always 0 or null, we consider it not a real drug delivery\n)\n-- we do not group by itemid in below query\n-- this is because we want to collapse all vasopressors together\n, vasocv_grp as\n(\nselect\n s1.icustay_id,\n s1.starttime,\n min(t1.endtime) as endtime\nfrom vasocv s1\ninner join vasocv t1\n on s1.icustay_id = t1.icustay_id\n and s1.starttime <= t1.endtime\n and not exists(select * from vasocv t2\n where t1.icustay_id = t2.icustay_id\n and t1.endtime >= t2.starttime\n and t1.endtime < t2.endtime)\nwhere not exists(select * from vasocv s2\n where s1.icustay_id = s2.icustay_id\n and s1.starttime > s2.starttime\n and s1.starttime <= s2.endtime)\ngroup by s1.icustay_id, s1.starttime\norder by s1.icustay_id, s1.starttime\n)\n-- now we extract the associated data for metavision patients\n-- do not need to group by itemid because we group by linkorderid\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , min(starttime) as starttime, max(endtime) as endtime\n from io_mv\n group by icustay_id, linkorderid\n)\n, vasomv_grp as\n(\nselect\n s1.icustay_id,\n s1.starttime,\n min(t1.endtime) as endtime\nfrom vasomv s1\ninner join vasomv t1\n on s1.icustay_id = t1.icustay_id\n and s1.starttime <= t1.endtime\n and not exists(select * from vasomv t2\n where t1.icustay_id = t2.icustay_id\n and t1.endtime >= t2.starttime\n and t1.endtime < t2.endtime)\nwhere not exists(select * from vasomv s2\n where s1.icustay_id = s2.icustay_id\n and s1.starttime > s2.starttime\n and s1.starttime <= s2.endtime)\ngroup by s1.icustay_id, s1.starttime\norder by s1.icustay_id, s1.starttime\n)\nselect\n icustay_id\n -- generate a sequential integer for convenience\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasocv_grp\n\nunion all\n\nselect\n icustay_id\n , row_number() over (partition by icustay_id order by starttime) as vasonum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\n -- add durations\nfrom\n vasomv_grp\n\norder by icustay_id, vasonum;\n-- jing add tail\nalter table mimic3.durations_vasopressor_durations\nowner to postgres;"
weight_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_weight_durations;\ncreate materialized view mimic3.durations_weight_durations\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts weights for adult icu patients with start/stop times\n-- if an admission weight is given, then this is assigned from intime to outtime\n\n-- this query extracts weights for adult icu patients with start/stop times\n-- if an admission weight is given, then this is assigned from intime to outtime\nwith wt_neonate as\n( \n select c.icustay_id, c.charttime\n , max(case when c.itemid = 3580 then c.valuenum end) as wt_kg\n , max(case when c.itemid = 3581 then c.valuenum end) as wt_lb\n , max(case when c.itemid = 3582 then c.valuenum end) as wt_oz\n from chartevents c\n where c.itemid in (3580, 3581, 3582)\n and c.icustay_id is not null\n and coalesce(c.error, 0) = 0\n -- wt_oz/wt_lb/wt_kg are only 0 erroneously, so drop these rows\n and c.valuenum > 0\n -- a separate query was run to manually verify only 1 value exists per\n -- icustay_id/charttime/itemid grouping\n -- therefore, we can use max() across itemid to collapse these values to 1 row per group\n group by c.icustay_id, c.charttime\n)\n, birth_wt as\n(\n select c.icustay_id, c.charttime\n , max(\n case\n when c.itemid = 4183 then\n -- clean free-text birth weight data\n case\n -- ignore value if there are any non-numeric characters\n when regexp_contains(c.value, '[^0-9\\\\.]') then null \n -- convert grams to kd\n when cast(c.value as numeric) > 100 then cast(c.value as numeric)/1000\n -- keep kg as is, filtering bad values (largest baby ever born was conveniently 9.98kg)\n when cast(c.value as numeric) < 10 then cast(c.value as numeric)\n -- ignore other values (those between 10-100) - junk data\n else null end\n -- itemid 3723 happily has all numeric data - also doesn't store any grams data\n when c.itemid = 3723 and c.valuenum < 10 then c.valuenum\n else null end) as wt_kg\n from chartevents c\n where c.itemid in (3723, 4183)\n and c.icustay_id is not null\n and coalesce(c.error, 0) = 0\n -- a separate query was run to manually verify only 1 value exists per\n -- icustay_id/charttime/itemid grouping\n -- therefore, we can use max() across itemid to collapse these values to 1 row per group\n group by c.icustay_id, c.charttime\n)\n, wt_stg as\n(\n select\n c.icustay_id\n , c.charttime\n , case when c.itemid in (762,226512) then 'admit'\n else 'daily' end as weight_type\n -- todo: eliminate obvious outliers if there is a reasonable weight\n , c.valuenum as weight\n from chartevents c\n where c.valuenum is not null\n and c.itemid in\n (\n 762,226512 -- admit wt\n , 763,224639 -- daily weight\n )\n and c.icustay_id is not null\n and c.valuenum > 0\n -- exclude rows marked as error\n and coalesce(c.error, 0) = 0\n union all\n select\n n.icustay_id\n , n.charttime\n , 'daily' as weight_type\n , case\n when wt_kg is not null then wt_kg\n when wt_lb is not null then wt_lb*0.45359237 + wt_oz*0.0283495231\n else null end as weight\n from wt_neonate n\n union all\n select\n
b.icustay_id\n , b.charttime\n
-- birth weight of neonates is treated as admission weight\n , 'admit' as weight_type\n , wt_kg as weight\n from birth_wt b\n)\n-- get more weights from echo - completes data for ~2500 patients\n-- we only use echo data if there is *no* charted data\n-- we impute the median echo weight for their entire icu stay\n, echo as\n(\n select\n ie.icustay_id\n , ec.charttime\n , text('echo') as weight_type\n , 0.453592*ec.weight as weight\n from icustays ie\n inner join echo_data ec\n on ie.hadm_id = ec.hadm_id\n where ec.weight is not null\n and ie.icustay_id not in (select distinct icustay_id from wt_stg)\n)\n, wt_stg0 as\n(\n select icustay_id, charttime, weight_type, weight\n from wt_stg\n union all\n select icustay_id, charttime, weight_type, weight\n from echo\n)\n-- assign ascending row number\n, wt_stg1 as\n(\n select\n icustay_id\n , charttime\n , weight_type\n , weight\n , row_number() over (partition by icustay_id, weight_type order by charttime) as rn\n from wt_stg0\n where weight is not null\n)\n-- change charttime to intime for the first admission weight recorded\n, wt_stg2 as\n(\n select \n wt_stg1.icustay_id\n , ie.intime, ie.outtime\n , case when wt_stg1.weight_type = 'admit' and wt_stg1.rn = 1\n then datetime_sub(ie.intime, interval '2' hour)\n else wt_stg1.charttime end as starttime\n , wt_stg1.weight\n from wt_stg1\n inner join icustays ie\n on ie.icustay_id = wt_stg1.icustay_id\n)\n, wt_stg3 as\n(\n select\n icustay_id\n , intime, outtime\n , starttime\n , coalesce(\n lead(starttime) over (partition by icustay_id order by starttime),\n datetime_add(greatest(outtime, starttime), interval '2' hour)\n ) as endtime\n , weight\n from wt_stg2\n)\n-- this table is the start/stop times from admit/daily weight in charted data\n, wt1 as\n(\n select\n icustay_id\n , starttime\n , coalesce(endtime,\n lead(starttime) over (partition by icustay_id order by starttime),\n -- impute icu discharge as the end of the final weight measurement\n -- plus a 2 hour \"fuzziness\" window\n datetime_add(outtime, interval '2' hour)\n ) as endtime\n , weight\n from wt_stg3\n)\n-- if the intime for the patient is < the first charted daily weight\n-- then we will have a \"gap\" at the start of their stay\n-- to prevent this, we look for these gaps and backfill the first weight\n-- this adds (153255-149657)=3598 rows, meaning this fix helps for up to 3598 icustay_id\n, wt_fix as\n(\n select ie.icustay_id\n -- we add a 2 hour \"fuzziness\" window\n , datetime_sub(ie.intime, interval '2' hour) as starttime\n , wt.starttime as endtime\n , wt.weight\n from icustays ie\n inner join\n -- the below subquery returns one row for each unique icustay_id\n -- the row contains: the first starttime and the corresponding weight\n (\n select wt1.icustay_id, wt1.starttime, wt1.weight\n , row_number() over (partition by wt1.icustay_id order by wt1.starttime) as rn\n from wt1\n ) wt\n on ie.icustay_id = wt.icustay_id\n and wt.rn = 1\n and ie.intime < wt.starttime\n)\n-- add the backfill rows to the main weight table\nselect\n wt1.icustay_id\n , wt1.starttime\n , wt1.endtime\n , wt1.weight\nfrom wt1\nunion all\nselect\n wt_fix.icustay_id\n , wt_fix.starttime\n , wt_fix.endtime\n , wt_fix.weight\nfrom wt_fix;\n-- jing add tail\nalter table mimic3.durations_weight_durations\nowner to postgres;"
arterial_line_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_arterial_line_durations;\ncreate materialized view mimic3.durations_arterial_line_durations\ntablespace pg_default\nas\n-- jing add head\nwith mv as\n(\n select\n pe.icustay_id\n , pe.starttime, pe.endtime\n , case\n when itemid in (225752, 224272)\n then 1\n when pe.locationcategory = 'invasive arterial'\n then 1\n when itemid = 225789 and pe.locationcategory is null\n then 1\n else 0\n end as arterial_line\n from procedureevents_mv pe\n where pe.itemid in\n (\n 224263 -- multi lumen | none | 12 | processes\n -- , 224264 -- picc line | none | 12 | processes\n , 224267 -- cordis/introducer | none | 12 | processes\n , 224268 -- trauma line | none | 12 | processes\n , 225199 -- triple introducer | none | 12 | processes\n -- , 225202 -- indwelling port (portacath) | none | 12 | processes\n -- , 225203 -- pheresis catheter | none | 12 | processes\n -- , 225315 -- tunneled (hickman) line | none | 12 | processes\n , 225752 -- arterial line | none | 12 | processes\n , 225789 -- sheath\n , 224272 -- iabp line\n -- , 227719 -- ava line | none | 12 | processes\n -- , 228286 -- intraosseous device | none | 12 | processes\n )\n)\n, cv_grp as\n(\n -- group type+site\n select ce.icustay_id, ce.charttime\n , max(case when itemid = 229 then value else null end) as inv1_type\n , max(case when itemid = 8392 then value else null end) as inv1_site\n , max(case when itemid = 235 then value else null end) as inv2_type\n , max(case when itemid = 8393 then value else null end) as inv2_site\n , max(case when itemid = 241 then value else null end) as inv3_type\n , max(case when itemid = 8394 then value else null end) as inv3_site\n , max(case when itemid = 247 then value else null end) as inv4_type\n , max(case when itemid = 8395 then value else null end) as inv4_site\n , max(case when itemid = 253 then value else null end) as inv5_type\n , max(case when itemid = 8396 then value else null end) as inv5_site\n , max(case when itemid = 259 then value else null end) as inv6_type\n , max(case when itemid = 8397 then value else null end) as inv6_site\n , max(case when itemid = 265 then value else null end) as inv7_type\n , max(case when itemid = 8398 then value else null end) as inv7_site\n , max(case when itemid = 271 then value else null end) as inv8_type\n , max(case when itemid = 8399 then value else null end) as inv8_site\n from chartevents ce\n where ce.itemid in\n (\n 229 -- inv line#1 [type]\n , 235 -- inv line#2 [type]\n , 241 -- inv line#3 [type]\n , 247 -- inv line#4 [type]\n , 253 -- inv line#5 [type]\n , 259 -- inv line#6 [type]\n , 265 -- inv line#7 [type]\n , 271 -- inv line#8 [type]\n , 8392 -- inv line#1 [site]\n , 8393 -- inv line#2 [site]\n , 8394 -- inv line#3 [site]\n , 8395 -- inv line#4 [site]\n , 8396 -- inv line#5 [site]\n , 8397 -- inv line#6 [site]\n , 8398 -- inv line#7 [site]\n , 8399 -- inv line#8 [site]\n )\n and ce.value is not null\n group by ce.icustay_id, ce.charttime\n)\n
-- types of invasive lines in carevue\n-- value | count\n-- ------------------+--------\n-- a-line | 460627\n-- multi-lumen | 345858\n-- picc line | 92285\n-- pa line | 65702\n-- dialysis line | 57579\n-- introducer | 36027\n-- cco pa line | 24831\n-- | 22369\n-- trauma line | 15530\n-- portacath | 12927\n-- ventriculostomy | 10295\n-- pre-sep catheter | 9678\n-- iabp | 8819\n-- other/remarks | 8725\n-- midline | 5067\n-- venous access | 4278\n-- hickman | 3783\n-- pacerintroducer | 2663\n-- tripleintroducer | 2262\n-- ric | 1625\n-- permacath | 1066\n-- camino bolt | 913\n-- lumbar drain | 361\n-- (23 rows)\n, cv as\n(\n select distinct icustay_id, charttime\n from cv_grp\n where (inv1_type in ('a-line', 'iabp'))\n or (inv2_type in ('a-line', 'iabp'))\n or (inv3_type in ('a-line', 'iabp'))\n or (inv4_type in ('a-line', 'iabp'))\n or (inv5_type in ('a-line', 'iabp'))\n or (inv6_type in ('a-line', 'iabp'))\n or (inv7_type in ('a-line', 'iabp'))\n or (inv8_type in ('a-line', 'iabp'))\n)\n-- transform carevue data into durations\n, cv0 as\n(\n select\n icustay_id\n -- this carries over the previous charttime\n , lag(charttime, 1) over (partition by icustay_id order by charttime) as charttime_lag\n , charttime\n from cv\n)\n, cv1 as\n(\n select\n icustay_id\n , charttime\n , charttime_lag\n -- if the current observation indicates a line is present\n -- calculate the time since the last charted line\n , charttime - charttime_lag as arterial_line_duration\n -- now we determine if the current line is \"new\"\n -- new == no documentation for 16 hours\n , case\n when datetime_diff(charttime, charttime_lag,'HOUR') > 16\n then 1\n else 0\n end as arterial_line_new\n from cv0\n)\n, cv2 as\n(\n select cv1.*\n -- create a cumulative sum of the instances of new events\n -- this results in a monotonic integer assigned to each new instance of a line\n , sum( arterial_line_new )\n over ( partition by icustay_id order by charttime )\n as arterial_line_rownum\n from cv1\n)\n-- create the durations for each line\n, cv_dur as\n(\n select icustay_id\n , arterial_line_rownum\n , min(charttime) as starttime\n , max(charttime) as endtime\n , datetime_diff(max(charttime), min(charttime),'HOUR') as duration_hours\n from cv2\n group by icustay_id, arterial_line_rownum\n having min(charttime) != max(charttime)\n)\nselect icustay_id\n -- , arterial_line_rownum\n , starttime, endtime, duration_hours\nfrom cv_dur\nunion all\n
--todo: collapse metavision durations if they overlap\nselect icustay_id\n -- , row_number() over (partition by icustay_id order by starttime) as arterial_line_rownum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\nfrom mv\nwhere arterial_line = 1\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_arterial_line_durations\nowner to postgres;"
central_line_durations <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_central_line_durations;\ncreate materialized view mimic3.durations_central_line_durations\ntablespace pg_default\nas\n-- jing add head\nwith mv as\n(\n select\n pe.icustay_id\n , pe.starttime, pe.endtime\n , case\n when (locationcategory <> 'invasive arterial' or locationcategory is null)\n then 1\n else 0\n end as central_line\n from procedureevents_mv pe\n where pe.itemid in\n (\n 224263 -- multi lumen | none | 12 | processes\n , 224264 -- picc line | none | 12 | processes\n , 224267 -- cordis/introducer | none | 12 | processes\n , 224268 -- trauma line | none | 12 | processes\n , 225199 -- triple introducer | none | 12 | processes\n , 225202 -- indwelling port (portacath) | none | 12 | processes\n , 225203 -- pheresis catheter | none | 12 | processes\n , 225315 -- tunneled (hickman) line | none | 12 | processes\n , 225752 -- arterial line | none | 12 | processes\n , 227719 -- ava line | none | 12 | processes\n -- , 228286 -- intraosseous device | none | 12 | processes\n , 224270 -- dialysis catheter\n )\n)\n, cv_grp as\n(\n -- group type+site\n select ce.icustay_id, ce.charttime\n , max(case when itemid = 229 then value else null end) as inv1_type\n , max(case when itemid = 8392 then value else null end) as inv1_site\n , max(case when itemid = 235 then value else null end) as inv2_type\n , max(case when itemid = 8393 then value else null end) as inv2_site\n , max(case when itemid = 241 then value else null end) as inv3_type\n , max(case when itemid = 8394 then value else null end) as inv3_site\n , max(case when itemid = 247 then value else null end) as inv4_type\n , max(case when itemid = 8395 then value else null end) as inv4_site\n , max(case when itemid = 253 then value else null end) as inv5_type\n , max(case when itemid = 8396 then value else null end) as inv5_site\n , max(case when itemid = 259 then value else null end) as inv6_type\n , max(case when itemid = 8397 then value else null end) as inv6_site\n , max(case when itemid = 265 then value else null end) as inv7_type\n , max(case when itemid = 8398 then value else null end) as inv7_site\n , max(case when itemid = 271 then value else null end) as inv8_type\n , max(case when itemid = 8399 then value else null end) as inv8_site\n from chartevents ce\n where ce.itemid in\n (\n 229 -- inv line#1 [type]\n , 235 -- inv line#2 [type]\n , 241 -- inv line#3 [type]\n , 247 -- inv line#4 [type]\n , 253 -- inv line#5 [type]\n , 259 -- inv line#6 [type]\n , 265 -- inv line#7 [type]\n , 271 -- inv line#8 [type]\n , 8392 -- inv line#1 [site]\n , 8393 -- inv line#2 [site]\n , 8394 -- inv line#3 [site]\n , 8395 -- inv line#4 [site]\n , 8396 -- inv line#5 [site]\n , 8397 -- inv line#6 [site]\n , 8398 -- inv line#7 [site]\n , 8399 -- inv line#8 [site]\n )\n and ce.value is not null\n group by ce.icustay_id, ce.charttime\n)\n-- types of invasive lines in carevue\n-- value | count\n-- ------------------+--------\n-- a-line | 460627\n-- multi-lumen | 345858\n-- picc line | 92285\n-- pa line | 65702\n-- dialysis line | 57579\n-- introducer | 36027\n-- cco pa line | 24831\n-- | 22369\n-- trauma line | 15530\n
-- portacath | 12927\n-- ventriculostomy | 10295\n-- pre-sep catheter | 9678\n-- iabp | 8819\n-- other/remarks | 8725\n-- midline | 5067\n-- venous access | 4278\n-- hickman | 3783\n-- pacerintroducer | 2663\n-- tripleintroducer | 2262\n-- ric | 1625\n-- permacath | 1066\n-- camino bolt | 913\n-- lumbar drain | 361\n-- (23 rows)\n, cv as\n(\n select distinct icustay_id, charttime\n from cv_grp\n where (inv1_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv2_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv3_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv4_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv5_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv6_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv7_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n or (inv8_type in ('multi-lumen', 'picc line', 'dialysis line', 'introducer','trauma line', 'portacath', 'venous access', 'hickman', 'pacerintroducer', 'tripleintroducer'))\n)\n-- transform carevue data into durations\n, cv0 as\n(\n select\n icustay_id\n -- this carries over the previous charttime\n , lag(charttime, 1) over (partition by icustay_id order by charttime) as charttime_lag\n , charttime\n from cv\n)\n, cv1 as\n(\n select\n icustay_id\n , charttime\n , charttime_lag\n -- if the current observation indicates a line is present\n -- calculate the time since the last charted line\n , charttime - charttime_lag as central_line_duration\n -- now we determine if the current line is \"new\"\n -- new == no documentation for 16 hours\n , case\n when datetime_diff(charttime, charttime_lag,'HOUR') > 16\n then 1\n else 0\n end as central_line_new\n from cv0\n)\n, cv2 as\n(\n select cv1.*\n -- create a cumulative sum of the instances of new events\n -- this results in a monotonic integer assigned to each new instance of a line\n , sum( central_line_new )\n over ( partition by icustay_id order by charttime )\n as central_line_rownum\n from cv1\n)\n-- create the durations for each line\n, cv_dur as\n(\n select icustay_id\n , central_line_rownum\n , min(charttime) as starttime\n , max(charttime) as endtime\n , datetime_diff(max(charttime), min(charttime),'HOUR') as duration_hours\n from cv2\n group by icustay_id, central_line_rownum\n having min(charttime) != max(charttime)\n)\nselect icustay_id\n -- , central_line_rownum\n , starttime, endtime, duration_hours\nfrom cv_dur\nunion all\n--todo: collapse metavision durations if they overlap\nselect icustay_id\n
-- , row_number() over (partition by icustay_id order by starttime) as central_line_rownum\n , starttime, endtime\n , datetime_diff(endtime, starttime,'HOUR') as duration_hours\nfrom mv\nwhere central_line = 1\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_central_line_durations\nowner to postgres;"
dobutamine_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_dobutamine_dose;\ncreate materialized view mimic3.durations_dobutamine_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of dopamine administration\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30042,30306) then 1 else 0 end) as vaso -- dobutamine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30042,30306) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30042,30306) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30042,30306) then rate else null end) as vaso_rate\n , max(case when itemid in (30042,30306) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in (30042,30306) -- dobutamine\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n
--when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\nselect\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n
-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , rate as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 221653 -- dobutamine\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_dobutamine_dose\nowner to postgres;"
dopamine_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_dopamine_dose;\ncreate materialized view mimic3.durations_dopamine_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of dopamine administration\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30043,30307) then 1 else 0 end) as vaso -- dopamine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30043,30307) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30043,30307) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30043,30307) then rate else null end) as vaso_rate\n , max(case when itemid in (30043,30307) then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid in\n (\n 30043,30307 -- dopamine\n )\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n
-- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\nselect\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n
-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , rate as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 221662 -- dopamine\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_dopamine_dose\nowner to postgres;"
epinephrine_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_epinephrine_dose;\ncreate materialized view mimic3.durations_epinephrine_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of epinephrine administration\n\n-- requires the weightfirstday table\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n cv.icustay_id, cv.charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30044,30119,30309) then 1 else 0 end) as vaso -- epinephrine\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30044,30119,30309) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid in (30044,30119,30309) and rate is not null then 1 else 0 end) as vaso_null\n , max(case\n when itemid = 30044 and wd.weight is null then rate / 80.0 -- super rare to be missing weight... affects 2 patients for 14 rows\n when itemid = 30044 then rate / wd.weight -- measured in mcgmin\n when itemid in (30119,30309) then rate -- measured in mcgkgmin\n else null\n end) as vaso_rate\n , max(case when itemid in (30044,30119,30309) then amount else null end) as vaso_amount\n\n from inputevents_cv cv\n left join durations_weight_durations wd\n on cv.icustay_id = wd.icustay_id\n and cv.charttime between wd.starttime and wd.endtime\n where itemid in\n (\n 30044,30119,30309 -- epinephrine\n )\n and cv.icustay_id is not null\n group by cv.icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n
-- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\nselect\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n
-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , rate as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 221289 -- epinephrine\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_epinephrine_dose\nowner to postgres;"
neuroblock_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_neuroblock_dose;\ncreate materialized view mimic3.durations_neuroblock_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of neuromuscular blocking agents\n-- note: we assume that injections will be filtered for carevue as they will have starttime = stopttime.\n\n-- get drug administration data from carevue and metavision\n-- metavision is simple and only requires one temporary table\nwith drugmv as\n(\n select\n icustay_id, orderid\n , rate as drug_rate\n , amount as drug_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid in\n (\n 222062 -- vecuronium (664 rows, 154 infusion rows)\n , 221555 -- cisatracurium (9334 rows, 8970 infusion rows)\n )\n and statusdescription != 'rewritten' -- only valid orders\n and rate is not null -- only continuous infusions\n)\n, drugcv1 as\n(\n select\n icustay_id, charttime\n -- where clause below ensures all rows are instance of the drug\n , 1 as drug\n \n -- the 'stopped' column indicates if a drug has been disconnected\n , max(case when stopped in ('stopped','d/c''d') then 1 else 0 end) as drug_stopped\n \n -- we only include continuous infusions, therefore expect a rate\n , max(case\n -- for \"free form\" entries (itemid >= 40000) rate is not available\n when itemid >= 40000 and amount is not null then 1\n when itemid < 40000 and rate is not null then 1\n else 0 end) as drug_null\n , max(case\n -- for \"free form\" entries (itemid >= 40000) rate is not available\n when itemid >= 40000 then coalesce(rate, amount)\n else rate end) as drug_rate\n , max(amount) as drug_amount\n from inputevents_cv\n where itemid in\n (\n 30114 -- cisatracurium (63994 rows)\n , 30138\t-- vecuronium\t (5160 rows)\n , 30113 -- atracurium (1163 rows)\n -- below rows are less frequent ad-hoc documentation, but worth including!\n , 42174\t-- nimbex cc/hr (207 rows)\n , 42385\t-- cisatracurium gtt (156 rows)\n , 41916\t-- nimbex\tinputevents_cv (136 rows)\n , 42100\t-- cistatracurium\t(132 rows)\n , 42045\t-- nimbex mcg/kg/min (78 rows)\n , 42246 -- cisatricarium cc/hr (70 rows)\n , 42291\t-- nimbex cc/hr (48 rows)\n , 42590\t-- nimbex\tinputevents_cv (38 rows)\n , 42284\t-- cisatracurium drip (9 rows)\n , 45096\t-- vecuronium drip (2 rows)\n )\n group by icustay_id, charttime\n union\n -- add data from chartevents\n select\n icustay_id, charttime\n -- where clause below ensures all rows are instance of the drug\n , 1 as drug\n \n -- the 'stopped' column indicates if a drug has been disconnected\n , max(case when stopped in ('stopped','d/c''d') then 1 else 0 end) as drug_stopped\n , max(case when valuenum <= 10 then 0 else 1 end) as drug_null\n \n -- educated guess!\n , max(case when valuenum <= 10 then valuenum else null end) as drug_rate\n , max(case when valuenum > 10 then valuenum else null end) as drug_amount\n from chartevents\n where itemid in\n (\n 1856 -- vecuronium mcg/min (8 rows)\n , 2164 -- nimbex mg/kg/hr (243 rows)\n , 2548 -- nimbex mg/kg/hr (103 rows)\n , 2285 -- nimbex mcg/kg/min (85 rows)\n , 2290 -- nimbex mcg/kg/m (32 rows)\n , 2670 -- nimbex (38 rows)\n , 2546
-- cisatracuriummg/kg/h (7 rows)\n , 1098 -- cisatracurium mg/kg (36 rows)\n , 2390 -- cisatracurium mg/hr (15 rows)\n , 2511 -- cisatracurium gtt (4 rows)\n , 1028 -- cisatracurium (208 rows)\n , 1858 -- cisatracurium (351 rows)\n )\n group by icustay_id, charttime\n \n)\n, drugcv2 as\n(\n select v.*\n , sum(drug_null) over (partition by icustay_id order by charttime) as drug_partition\n from\n drugcv1 v\n)\n, drugcv3 as\n(\n select v.*\n , first_value(drug_rate) over (partition by icustay_id, drug_partition order by charttime) as drug_prevrate_ifnull\n from\n drugcv2 v\n)\n, drugcv4 as\n(\n select\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, drug order by charttime))) as delta\n \n , drug\n , drug_rate\n , drug_amount\n , drug_stopped\n , drug_prevrate_ifnull\n \n -- we define start time here\n , case\n when drug = 0 then null\n \n -- if this is the first instance of the drug\n when drug_rate > 0 and\n lag(drug_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, drug, drug_null\n order by charttime\n )\n is null\n then 1\n \n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes drugnum sequential\n when drug_rate = 0 and\n lag(drug_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, drug\n order by charttime\n )\n = 0\n then 0\n \n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- drug_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when drug_prevrate_ifnull = 0 and\n lag(drug_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, drug\n order by charttime\n )\n = 0\n then 0\n \n -- if the last recorded rate was 0, newdrug = 1\n when lag(drug_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, drug\n order by charttime\n ) = 0\n then 1\n \n -- if the last recorded drug was d/c'd, newdrug = 1\n when\n lag(drug_stopped,1)\n over\n (\n partition by icustay_id, drug\n order by charttime\n )\n = 1 then 1\n\n when (charttime - (lag(charttime, 1) over (partition by icustay_id, drug order by charttime))) > (interval '8 hours') then 1\n else null\n end as drug_start\n\nfrom\n drugcv3\n)\n-- propagate start/stop flags forward in time\n, drugcv5 as\n(\n select v.*\n , sum(drug_start) over (partition by icustay_id, drug order by charttime) as drug_first\nfrom\n drugcv4 v\n)\n, drugcv6 as\n(\n select v.*\n -- we define end time here\n , case\n when drug = 0\n then null\n\n -- if the recorded drug was d/c'd, this is an end time\n when drug_stopped = 1\n then drug_first\n \n -- if the rate is zero, this is the end time\n when drug_rate = 0\n then drug_first\n \n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on drug\n -- in principle, this could add an extra end time for the drug\n -- however, since we later group on drug_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, drug\n order by charttime\n ) is null\n then drug_first\n \n else null\n end as drug_stop\n from drugcv5 v\n)\n\n
-- -- if you want to look at the results of the table before grouping:\n -- select\n-- icustay_id, charttime, drug, drug_rate, drug_amount\n-- , drug_stopped\n-- , drug_start\n-- , drug_first\n-- , drug_stop\n-- from drugcv6 order by icustay_id, charttime;\n\n, drugcv7 as\n(\n select\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, drug_first order by charttime) as endtime\n , drug, drug_rate, drug_amount, drug_stop, drug_start, drug_first\n from drugcv6\n where\n drug_first is not null -- bogus data\n and\n drug_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\n and\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, drugcv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , drug, drug_rate, drug_amount, drug_stop, drug_start, drug_first\n from drugcv7\n where endtime is not null\n and drug_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, drugcv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(drug_rate) over (partition by icustay_id order by starttime, endtime) = drug_rate\n then 0\n else 1\n end as drug_groups\n , drug, drug_rate, drug_amount, drug_stop, drug_start, drug_first\n from drugcv8\n where endtime is not null\n and drug_rate > 0\n and starttime != endtime\n)\n, drugcv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , drug_groups\n , sum(drug_groups) over (partition by icustay_id order by starttime, endtime) as drug_groups_sum\n , drug, drug_rate, drug_amount, drug_stop, drug_start, drug_first\n from drugcv9\n)\n, drugcv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , drug_groups_sum\n , drug_rate\n , sum(drug_amount) as drug_amount\n from drugcv10\n group by icustay_id, drug_groups_sum, drug_rate\n)\n-- now assign this data to every hour of the patient's stay\n-- drug_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , drug_rate, drug_amount\nfrom drugcv\nunion\nselect icustay_id\n , starttime, endtime\n , drug_rate, drug_amount\nfrom drugmv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_neuroblock_dose\nowner to postgres;\n"
norepinephrine_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_norepinephrine_dose;\ncreate materialized view mimic3.durations_norepinephrine_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of norepinephrine administration\n-- Total time on the drug can be calculated from this table by grouping using icustay_id\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n cv.icustay_id, cv.charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30047,30120) then 1 else 0 end) as vaso -- norepinephrine\n \n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30047,30120) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n \n -- case statement determining whether the itemid is an instance of vasopressor usage\n \n , max(case when itemid in (30047,30120) and rate is not null then 1 else 0 end) as vaso_null\n , max(case\n when itemid = 30047 and wd.weight is null then rate / 80.0 -- this is rare, only affects a total of ~400 rows\n when itemid = 30047 then rate / wd.weight -- measured in mcgmin\n when itemid = 30120 then rate -- measured in mcgkgmin ** there are clear errors, perhaps actually mcgmin\n else null end) as vaso_rate\n , max(case when itemid in (30047,30120) then amount else null end) as vaso_amount\n \n from inputevents_cv cv\n left join durations_weight_durations wd\n on cv.icustay_id = wd.icustay_id\n and cv.charttime between wd.starttime and wd.endtime\n where itemid in (30047,30120) -- norepinephrine\n and cv.icustay_id is not null\n group by cv.icustay_id, cv.charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\n select\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n \n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n \n -- we define start time here\n , case\n when vaso = 0 then null\n \n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n \n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n \n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n \n
-- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n \n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n \n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n \n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n \n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n -- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\n select\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv6\n where\n vaso_first is not null -- bogus data\n and\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\n and\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n
-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , rate as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 221906 -- norepinephrine\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_norepinephrine_dose\nowner to postgres;\n"
vasopressin_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_vasopressin_dose;\ncreate materialized view mimic3.durations_vasopressin_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of vasopressin administration\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid = 30051 then 1 else 0 end) as vaso -- vasopressin\n\n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid = 30051 and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n\n , max(case when itemid = 30051 and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid = 30051 then rate else null end) as vaso_rate\n , max(case when itemid = 30051 then amount else null end) as vaso_amount\n\n from inputevents_cv\n where itemid = 30051 -- vasopressin\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\nselect\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n\n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n\n -- we define start time here\n , case\n when vaso = 0 then null\n\n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n\n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n\n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n\n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n -- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n\n
-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n\n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n\n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n -- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n\n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n-- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\nselect\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\nfrom vasocv6\nwhere\n vaso_first is not null -- bogus data\nand\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\nand\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , case when rateuom = 'units/min' then rate*60.0 else rate end as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 222315 -- vasopressin\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_vasopressin_dose\nowner to postgres;"
phenylephrine_dose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS durations_phenylephrine_dose;\ncreate materialized view mimic3.durations_phenylephrine_dose\ntablespace pg_default\nas\n-- jing add head\n-- this query extracts dose+durations of phenylephrine administration\n\n-- get drug administration data from carevue first\nwith vasocv1 as\n(\n select\n icustay_id, charttime\n -- case statement determining whether the itemid is an instance of vasopressor usage\n , max(case when itemid in (30127,30128) then 1 else 0 end) as vaso -- phenylephrine\n \n -- the 'stopped' column indicates if a vasopressor has been disconnected\n , max(case when itemid in (30127,30128) and (stopped = 'stopped' or stopped like 'd/c%') then 1\n else 0 end) as vaso_stopped\n \n , max(case when itemid in (30127,30128) and rate is not null then 1 else 0 end) as vaso_null\n , max(case when itemid in (30127,30128) then rate else null end) as vaso_rate\n , max(case when itemid in (30127,30128) then amount else null end) as vaso_amount\n \n from inputevents_cv\n where itemid in (30127,30128) -- phenylephrine\n group by icustay_id, charttime\n)\n, vasocv2 as\n(\n select v.*\n , sum(vaso_null) over (partition by icustay_id order by charttime) as vaso_partition\n from\n vasocv1 v\n)\n, vasocv3 as\n(\n select v.*\n , first_value(vaso_rate) over (partition by icustay_id, vaso_partition order by charttime) as vaso_prevrate_ifnull\n from\n vasocv2 v\n)\n, vasocv4 as\n(\n select\n icustay_id\n , charttime\n -- , (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) as delta\n \n , vaso\n , vaso_rate\n , vaso_amount\n , vaso_stopped\n , vaso_prevrate_ifnull\n \n -- we define start time here\n , case\n when vaso = 0 then null\n \n -- if this is the first instance of the vasoactive drug\n when vaso_rate > 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso, vaso_null\n order by charttime\n )\n is null\n then 1\n \n -- you often get a string of 0s\n -- we decide not to set these as 1, just because it makes vasonum sequential\n when vaso_rate = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n \n -- sometimes you get a string of null, associated with 0 volumes\n -- same reason as before, we decide not to set these as 1\n -- vaso_prevrate_ifnull is equal to the previous value *iff* the current value is null\n when vaso_prevrate_ifnull = 0 and\n lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 0\n then 0\n \n -- if the last recorded rate was 0, newvaso = 1\n when lag(vaso_prevrate_ifnull,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) = 0\n then 1\n \n -- if the last recorded vaso was d/c'd, newvaso = 1\n when\n lag(vaso_stopped,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n )\n = 1 then 1\n\n
-- ** not sure if the below is needed\n --when (charttime - (lag(charttime, 1) over (partition by icustay_id, vaso order by charttime))) > (interval '4 hours') then 1\n else null\n end as vaso_start\n\nfrom\n vasocv3\n)\n-- propagate start/stop flags forward in time\n, vasocv5 as\n(\n select v.*\n , sum(vaso_start) over (partition by icustay_id, vaso order by charttime) as vaso_first\nfrom\n vasocv4 v\n)\n, vasocv6 as\n(\n select v.*\n -- we define end time here\n , case\n when vaso = 0\n then null\n\n -- if the recorded vaso was d/c'd, this is an end time\n when vaso_stopped = 1\n then vaso_first\n \n -- if the rate is zero, this is the end time\n when vaso_rate = 0\n then vaso_first\n \n -- the last row in the table is always a potential end time\n -- this captures patients who die/are discharged while on vasopressors\n
-- in principle, this could add an extra end time for the vasopressor\n -- however, since we later group on vaso_start, any extra end times are ignored\n when lead(charttime,1)\n over\n (\n partition by icustay_id, vaso\n order by charttime\n ) is null\n then vaso_first\n \n else null\n end as vaso_stop\n from vasocv5 v\n)\n\n-- -- if you want to look at the results of the table before grouping:\n -- select\n-- icustay_id, charttime, vaso, vaso_rate, vaso_amount\n-- , vaso_stopped\n-- , vaso_start\n-- , vaso_first\n-- , vaso_stop\n-- from vasocv6 order by icustay_id, charttime;\n\n, vasocv7 as\n(\n select\n icustay_id\n , charttime as starttime\n , lead(charttime) over (partition by icustay_id, vaso_first order by charttime) as endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv6\n where\n vaso_first is not null -- bogus data\n and\n vaso_first != 0 -- sometimes *only* a rate of 0 appears, i.e. the drug is never actually delivered\n and\n icustay_id is not null -- there are data for \"floating\" admissions, we don't worry about these\n)\n-- table of start/stop times for event\n, vasocv8 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv7\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n-- collapse these start/stop times down if the rate doesn't change\n, vasocv9 as\n(\n select\n icustay_id\n , starttime, endtime\n , case\n when lag(endtime) over (partition by icustay_id order by starttime, endtime) = starttime\n and lag(vaso_rate) over (partition by icustay_id order by starttime, endtime) = vaso_rate\n then 0\n else 1\n end as vaso_groups\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv8\n where endtime is not null\n and vaso_rate > 0\n and starttime != endtime\n)\n, vasocv10 as\n(\n select\n icustay_id\n , starttime, endtime\n , vaso_groups\n , sum(vaso_groups) over (partition by icustay_id order by starttime, endtime) as vaso_groups_sum\n , vaso, vaso_rate, vaso_amount, vaso_stop, vaso_start, vaso_first\n from vasocv9\n)\n, vasocv as\n(\n select icustay_id\n , min(starttime) as starttime\n , max(endtime) as endtime\n , vaso_groups_sum\n , vaso_rate\n , sum(vaso_amount) as vaso_amount\n from vasocv10\n group by icustay_id, vaso_groups_sum, vaso_rate\n)\n-- now we extract the associated data for metavision patients\n, vasomv as\n(\n select\n icustay_id, linkorderid\n , rate as vaso_rate\n , amount as vaso_amount\n , starttime\n , endtime\n from inputevents_mv\n where itemid = 221749 -- phenylephrine\n and statusdescription != 'rewritten' -- only valid orders\n)\n-- now assign this data to every hour of the patient's stay\n-- vaso_amount for carevue is not accurate\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasocv\nunion all\nselect icustay_id\n , starttime, endtime\n , vaso_rate, vaso_amount\nfrom vasomv\norder by icustay_id, starttime;\n-- jing add tail\nalter table mimic3.durations_phenylephrine_dose\nowner to postgres;\n"
# 5 comorbidity -----
elixhauser_ahrq_v37 <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS comorbidity_elixhauser_ahrq_v37;\ncreate materialized view mimic3.comorbidity_elixhauser_ahrq_v37\ntablespace pg_default\nas\n-- jing add head\n-- This code uses the latest version of Elixhauser provided by AHRQ\n\nwith eliflg as\n(\nselect hadm_id, seq_num, icd9_code\n-- note that these codes will seem incomplete at first\n-- for example, CHF is missing a lot of codes referenced in the literature (402.11, 402.91, etc)\n-- these codes are captured by hypertension flags instead\n-- later there are some complicated rules which confirm/reject those codes as chf\n, CASE\n when icd9_code = '39891' then 1\n when icd9_code between '4280' and '4289' then 1\n\t\tend as chf /* Congestive heart failure */\n\n-- cardiac arrhythmias is removed in up to date versions\n, case\n when icd9_code = '42610' then 1\n when icd9_code = '42611' then 1\n when icd9_code = '42613' then 1\n when icd9_code between '4262' and '42653' then 1\n when icd9_code between '4266' and '42689' then 1\n when icd9_code = '4270' then 1\n when icd9_code = '4272' then 1\n when icd9_code = '42731' then 1\n when icd9_code = '42760' then 1\n when icd9_code = '4279' then 1\n when icd9_code = '7850' then 1\n when icd9_code between 'V450' and 'V4509' then 1\n when icd9_code between 'V533' and 'V5339' then 1\n end as arythm /* Cardiac arrhythmias */\n\n, CASE\n when icd9_code between '09320' and '09324' then 1\n when icd9_code between '3940' and '3971' then 1\n when icd9_code = '3979' then 1\n when icd9_code between '4240' and '42499' then 1\n when icd9_code between '7463' and '7466' then 1\n when icd9_code = 'V422' then 1\n when icd9_code = 'V433' then 1\n\t\tend as valve /* Valvular disease */\n\n, CASE\n when icd9_code between '41511' and '41519' then 1\n when icd9_code between '4160' and '4169' then 1\n when icd9_code = '4179' then 1\n\t\tend as pulmcirc /* Pulmonary circulation disorder */\n\n, CASE\n when icd9_code between '4400' and '4409' then 1\n when icd9_code between '44100' and '4419' then 1\n when icd9_code between '4420' and '4429' then 1\n when icd9_code between '4431' and '4439' then 1\n when icd9_code between '44421' and '44422' then 1\n when icd9_code = '4471' then 1\n when icd9_code = '449' then 1\n when icd9_code = '5571' then 1\n when icd9_code = '5579' then 1\n when icd9_code = 'V434' then 1\n\t\tend as perivasc /* Peripheral vascular disorder */\n\n, CASE\n when icd9_code = '4011' then 1\n when icd9_code = '4019' then 1\n when icd9_code between '64200' and '64204' then 1\n\t\tend as htn /* Hypertension, uncomplicated */\n\n, CASE\n when icd9_code = '4010' then 1\n when icd9_code = '4372' then 1\n\t\tend as htncx /* Hypertension, complicated */\n\n\n /******************************************************************/\n /* The following are special, temporary formats used in the */\n /* creation of the hypertension complicated comorbidity when */\n /* overlapping with congestive heart failure or renal failure */\n /* occurs. These temporary formats are referenced in the program */\n /* called comoanaly2009.txt. */\n /******************************************************************/\n,
CASE\n when icd9_code between '64220' and '64224' then 1\n\t\tend as htnpreg /* Pre-existing hypertension complicating pregnancy */\n\n, CASE\n when icd9_code = '40200' then 1\n when icd9_code = '40210' then 1\n when icd9_code = '40290' then 1\n when icd9_code = '40509' then 1\n when icd9_code = '40519' then 1\n when icd9_code = '40599' then 1\n\t\tend as htnwochf /* Hypertensive heart disease without heart failure */\n\n, CASE\n when icd9_code = '40201' then 1\n when icd9_code = '40211' then 1\n when icd9_code = '40291' then 1\n\t\tend as htnwchf /* Hypertensive heart disease with heart failure */\n\n, CASE\n when icd9_code = '40300' then 1\n when icd9_code = '40310' then 1\n when icd9_code = '40390' then 1\n when icd9_code = '40501' then 1\n when icd9_code = '40511' then 1\n when icd9_code = '40591' then 1\n when icd9_code between '64210' and '64214' then 1\n\t\tend as hrenworf /* Hypertensive renal disease without renal failure */\n\n, CASE\n when icd9_code = '40301' then 1\n when icd9_code = '40311' then 1\n when icd9_code = '40391' then 1\n\t\tend as hrenwrf /* Hypertensive renal disease with renal failure */\n\n, CASE\n when icd9_code = '40400' then 1\n when icd9_code = '40410' then 1\n when icd9_code = '40490' then 1\n\t\tend as hhrwohrf /* Hypertensive heart and renal disease without heart or renal failure */\n\n, CASE\n when icd9_code = '40401' then 1\n when icd9_code = '40411' then 1\n when icd9_code = '40491' then 1\n\t\tend as hhrwchf /* Hypertensive heart and renal disease with heart failure */\n\n, CASE\n when icd9_code = '40402' then 1\n when icd9_code = '40412' then 1\n when icd9_code = '40492' then 1\n\t\tend as hhrwrf /* Hypertensive heart and renal disease with renal failure */\n\n, CASE\n when icd9_code = '40403' then 1\n when icd9_code = '40413' then 1\n when icd9_code = '40493' then 1\n\t\tend as hhrwhrf /* Hypertensive heart and renal disease with heart and renal failure */\n\n, CASE\n when icd9_code between '64270' and '64274' then 1\n when icd9_code between '64290' and '64294' then 1\n\t\tend as ohtnpreg /* Other hypertension in pregnancy */\n\n /******************** End temporary Formats ***********************/\n\n,
CASE\n when icd9_code between '3420' and '3449' then 1\n when icd9_code between '43820' and '43853' then 1\n when icd9_code = '78072' then 1\n\t\tend as para /* Paralysis */\n\n, CASE\n when icd9_code between '3300' and '3319' then 1\n when icd9_code = '3320' then 1\n when icd9_code = '3334' then 1\n when icd9_code = '3335' then 1\n when icd9_code = '3337' then 1\n when icd9_code in ('33371','33372','33379','33385','33394') then 1\n when icd9_code between '3340' and '3359' then 1\n when icd9_code = '3380' then 1\n when icd9_code = '340' then 1\n when icd9_code between '3411' and '3419' then 1\n when icd9_code between '34500' and '34511' then 1\n when icd9_code between '3452' and '3453' then 1\n when icd9_code between '34540' and '34591' then 1\n when icd9_code between '34700' and '34701' then 1\n when icd9_code between '34710' and '34711' then 1\n when icd9_code = '3483' then 1 -- discontinued icd-9\n when icd9_code between '64940' and '64944' then 1\n when icd9_code = '7687' then 1\n when icd9_code between '76870' and '76873' then 1\n when icd9_code = '7803' then 1\n when icd9_code = '78031' then 1\n when icd9_code = '78032' then 1\n when icd9_code = '78033' then 1\n when icd9_code = '78039' then 1\n when icd9_code = '78097' then 1\n when icd9_code = '7843' then 1\n\t\tend as neuro /* Other neurological */\n\n, CASE\n when icd9_code between '490' and '4928' then 1\n when icd9_code between '49300' and '49392' then 1\n when icd9_code between '494' and '4941' then 1\n when icd9_code between '4950' and '505' then 1\n when icd9_code = '5064' then 1\n\t\tend as chrnlung /* Chronic pulmonary disease */\n\n, CASE\n when icd9_code between '25000' and '25033' then 1\n when icd9_code between '64800' and '64804' then 1\n when icd9_code between '24900' and '24931' then 1\n\t\tend as dm /* Diabetes w/o chronic complications*/\n\n, CASE\n when icd9_code between '25040' and '25093' then 1\n when icd9_code = '7751' then 1\n when icd9_code between '24940' and '24991' then 1\n\t\tend as dmcx /* Diabetes w/ chronic complications */\n\n, CASE\n when icd9_code between '243' and '2442' then 1\n when icd9_code = '2448' then 1\n when icd9_code = '2449' then 1\n\t\tend as hypothy /* Hypothyroidism */\n\n, CASE\n when icd9_code = '585' then 1 -- discontinued code\n when icd9_code = '5853' then 1\n when icd9_code = '5854' then 1\n when icd9_code = '5855' then 1\n when icd9_code = '5856' then 1\n when icd9_code = '5859' then 1\n when icd9_code = '586' then 1\n when icd9_code = 'V420' then 1\n when icd9_code = 'V451' then 1\n when icd9_code between 'V560' and 'V5632' then 1\n when icd9_code = 'V568' then 1\n when icd9_code between 'V4511' and 'V4512' then 1\n\t\tend as renlfail /* Renal failure */\n\n,
CASE\n when icd9_code = '07022' then 1\n when icd9_code = '07023' then 1\n when icd9_code = '07032' then 1\n when icd9_code = '07033' then 1\n when icd9_code = '07044' then 1\n when icd9_code = '07054' then 1\n when icd9_code = '4560' then 1\n when icd9_code = '4561' then 1\n when icd9_code = '45620' then 1\n when icd9_code = '45621' then 1\n when icd9_code = '5710' then 1\n when icd9_code = '5712' then 1\n when icd9_code = '5713' then 1\n when icd9_code between '57140' and '57149' then 1\n when icd9_code = '5715' then 1\n when icd9_code = '5716' then 1\n when icd9_code = '5718' then 1\n when icd9_code = '5719' then 1\n when icd9_code = '5723' then 1\n when icd9_code = '5728' then 1\n when icd9_code = '5735' then 1\n when icd9_code = 'V427' then 1\n\t\tend as liver /* Liver disease */\n\n, CASE\n when icd9_code = '53141' then 1\n when icd9_code = '53151' then 1\n when icd9_code = '53161' then 1\n when icd9_code = '53170' then 1\n when icd9_code = '53171' then 1\n when icd9_code = '53191' then 1\n when icd9_code = '53241' then 1\n when icd9_code = '53251' then 1\n when icd9_code = '53261' then 1\n when icd9_code = '53270' then 1\n when icd9_code = '53271' then 1\n when icd9_code = '53291' then 1\n when icd9_code = '53341' then 1\n when icd9_code = '53351' then 1\n when icd9_code = '53361' then 1\n when icd9_code = '53370' then 1\n when icd9_code = '53371' then 1\n when icd9_code = '53391' then 1\n when icd9_code = '53441' then 1\n when icd9_code = '53451' then 1\n when icd9_code = '53461' then 1\n when icd9_code = '53470' then 1\n when icd9_code = '53471' then 1\n when icd9_code = '53491' then 1\n\t\tend as ulcer /* Chronic Peptic ulcer disease (includes bleeding only if obstruction is also present) */\n\n, CASE\n when icd9_code between '042' and '0449' then 1\n\t\tend as aids /* HIV and AIDS */\n\n, CASE\n when icd9_code between '20000' and '20238' then 1\n when icd9_code between '20250' and '20301' then 1\n when icd9_code = '2386' then 1\n when icd9_code = '2733' then 1\n when icd9_code between '20302' and '20382' then 1\n\t\tend as lymph /* Lymphoma */\n\n, CASE\n when icd9_code between '1960' and '1991' then 1\n when icd9_code between '20970' and '20975' then 1\n when icd9_code = '20979' then 1\n when icd9_code = '78951' then 1\n\t\tend as mets /* Metastatic cancer */\n\n, CASE\n when icd9_code between '1400' and '1729' then 1\n when icd9_code between '1740' and '1759' then 1\n when icd9_code between '179' and '1958' then 1\n when icd9_code between '20900' and '20924' then 1\n when icd9_code between '20925' and '2093' then 1\n when icd9_code between '20930' and '20936' then 1\n when icd9_code between '25801' and '25803' then 1\n\t\tend as tumor /* Solid tumor without metastasis */\n\n,
CASE\n when icd9_code = '7010' then 1\n when icd9_code between '7100' and '7109' then 1\n when icd9_code between '7140' and '7149' then 1\n when icd9_code between '7200' and '7209' then 1\n when icd9_code = '725' then 1\n\t\tend as arth /* Rheumatoid arthritis/collagen vascular diseases */\n\n, CASE\n when icd9_code between '2860' and '2869' then 1\n when icd9_code = '2871' then 1\n when icd9_code between '2873' and '2875' then 1\n when icd9_code between '64930' and '64934' then 1\n when icd9_code = '28984' then 1\n\t\tend as coag /* Coagulation deficiency */\n\n, CASE\n when icd9_code = '2780' then 1\n when icd9_code = '27800' then 1\n when icd9_code = '27801' then 1\n when icd9_code = '27803' then 1\n when icd9_code between '64910' and '64914' then 1\n when icd9_code between 'V8530' and 'V8539' then 1\n when icd9_code = 'V854' then 1 -- hierarchy used for AHRQ v3.6 and earlier\n when icd9_code between 'V8541' and 'V8545' then 1\n when icd9_code = 'V8554' then 1\n when icd9_code = '79391' then 1\n\t\tend as obese /* Obesity */\n\n, CASE\n when icd9_code between '260' and '2639' then 1\n when icd9_code between '78321' and '78322' then 1\n\t\tend as wghtloss /* Weight loss */\n\n, CASE\n when icd9_code between '2760' and '2769' then 1\n\t\tend as lytes /* Fluid and electrolyte disorders - note:\n this comorbidity should be dropped when\n used with the AHRQ Patient Safety Indicators*/\n, CASE\n when icd9_code = '2800' then 1\n when icd9_code between '64820' and '64824' then 1\n\t\tend as bldloss /* Blood loss anemia */\n\n, CASE\n when icd9_code between '2801' and '2819' then 1\n when icd9_code between '28521' and '28529' then 1\n when icd9_code = '2859' then 1\n\t\tend as anemdef /* Deficiency anemias */\n\n, CASE\n when icd9_code between '2910' and '2913' then 1\n when icd9_code = '2915' then 1\n when icd9_code = '2918' then 1\n when icd9_code = '29181' then 1\n when icd9_code = '29182' then 1\n when icd9_code = '29189' then 1\n when icd9_code = '2919' then 1\n when icd9_code between '30300' and '30393' then 1\n when icd9_code between '30500' and '30503' then 1\n\t\tend as alcohol /* Alcohol abuse */\n\n, CASE\n when icd9_code = '2920' then 1\n when icd9_code between '29282' and '29289' then 1\n when icd9_code = '2929' then 1\n when icd9_code between '30400' and '30493' then 1\n when icd9_code between '30520' and '30593' then 1\n when icd9_code between '64830' and '64834' then 1\n\t\tend as drug /* Drug abuse */\n\n, CASE\n when icd9_code between '29500' and '2989' then 1\n when icd9_code = '29910' then 1\n when icd9_code = '29911' then 1\n\t\tend as psych /* Psychoses */\n\n,
CASE\n when icd9_code = '3004' then 1\n when icd9_code = '30112' then 1\n when icd9_code = '3090' then 1\n when icd9_code = '3091' then 1\n when icd9_code = '311' then 1\n\t\tend as depress /* Depression */\nfrom diagnoses_icd icd\nWHERE seq_num = 1\n)\n-- collapse the icd9_code specific flags into hadm_id specific flags\n-- this groups comorbidities together for a single patient admission\n, eligrp as\n(\n select hadm_id\n , max(chf) as chf\n , max(arythm) as arythm\n , max(valve) as valve\n , max(pulmcirc) as pulmcirc\n , max(perivasc) as perivasc\n , max(htn) as htn\n , max(htncx) as htncx\n , max(htnpreg) as htnpreg\n , max(htnwochf) as htnwochf\n , max(htnwchf) as htnwchf\n , max(hrenworf) as hrenworf\n , max(hrenwrf) as hrenwrf\n , max(hhrwohrf) as hhrwohrf\n , max(hhrwchf) as hhrwchf\n , max(hhrwrf) as hhrwrf\n , max(hhrwhrf) as hhrwhrf\n , max(ohtnpreg) as ohtnpreg\n , max(para) as para\n , max(neuro) as neuro\n , max(chrnlung) as chrnlung\n , max(dm) as dm\n , max(dmcx) as dmcx\n , max(hypothy) as hypothy\n , max(renlfail) as renlfail\n , max(liver) as liver\n , max(ulcer) as ulcer\n , max(aids) as aids\n , max(lymph) as lymph\n , max(mets) as mets\n , max(tumor) as tumor\n , max(arth) as arth\n , max(coag) as coag\n , max(obese) as obese\n , max(wghtloss) as wghtloss\n , max(lytes) as lytes\n , max(bldloss) as bldloss\n , max(anemdef) as anemdef\n , max(alcohol) as alcohol\n , max(drug) as drug\n , max(psych) as psych\n , max(depress) as depress\nfrom eliflg\ngroup by hadm_id\n)\n\n-- DRG FILTER --\n, msdrg as\n(\nselect\n hadm_id\n/**** V29 MS-DRG Formats ****/\n\n/* Cardiac */\n, case\n when d.drg_code between 001 and 002 then 1\n when d.drg_code between 215 and 238 then 1\n when d.drg_code between 242 and 252 then 1\n when d.drg_code between 253 and 254 then 1\n when d.drg_code between 258 and 262 then 1\n when d.drg_code between 265 and 267 then 1\n when d.drg_code between 280 and 293 then 1\n when d.drg_code between 296 and 298 then 1\n when d.drg_code between 302 and 303 then 1\n when d.drg_code between 306 and 313 then 1\nelse 0 end as carddrg\n\n/* Peripheral vascular */\n, case\n when d.drg_code between 299 and 301 then 1\nelse 0 end as peridrg\n\n/* Renal */\n, case\n when d.drg_code = 652 then 1\n when d.drg_code between 656 and 661 then 1\n when d.drg_code between 673 and 675 then 1\n when d.drg_code between 682 and 700 then 1\nelse 0 end as renaldrg\n\n/* Nervous system */\n, case\n when d.drg_code between 020 and 042 then 1\n when d.drg_code between 052 and 103 then 1\nelse 0 end as nervdrg\n\n/* Cerebrovascular */\n, case\n when d.drg_code between 020 and 022 then 1\n when d.drg_code between 034 and 039 then 1\n when d.drg_code between 064 and 072 then 1\nelse 0 end as ceredrg\n\n/* COPD asthma */\n,
case\n when d.drg_code between 190 and 192 then 1\n when d.drg_code between 202 and 203 then 1\nelse 0 end as pulmdrg\n\n/* Diabetes */\n, case\n when d.drg_code between 637 and 639 then 1\nelse 0 end as DIABDRG\n\n/* Thyroid endocrine */\n, case\n when d.drg_code between 625 and 627 then 1\n when d.drg_code between 643 and 645 then 1\nelse 0 end as hypodrg\n\n/* Kidney transp, renal fail/dialysis */\n, case\n when d.drg_code = 652 then 1\n when d.drg_code between 682 and 685 then 1\nelse 0 end as renfdrg\n\n/* Liver */\n, case\n when d.drg_code between 420 and 425 then 1\n when d.drg_code between 432 and 434 then 1\n when d.drg_code between 441 and 446 then 1\nelse 0 end as liverdrg\n\n/* GI hemorrhage or ulcer */\n, case\n when d.drg_code between 377 and 384 then 1\nelse 0 end as ulcedrg\n\n/* Human immunodeficiency virus */\n, case\n when d.drg_code between 969 and 970 then 1\n when d.drg_code between 974 and 977 then 1\nelse 0 end as hivdrg\n\n/* Leukemia/lymphoma */\n, case\n when d.drg_code between 820 and 830 then 1\n when d.drg_code between 834 and 849 then 1\nelse 0 end as leukdrg\n\n/* Cancer, lymphoma */\n, case\n when d.drg_code = 054 then 1\n when d.drg_code = 055 then 1\n when d.drg_code between 146 and 148 then 1\n when d.drg_code between 180 and 182 then 1\n when d.drg_code between 374 and 376 then 1\n when d.drg_code between 435 and 437 then 1\n when d.drg_code between 542 and 544 then 1\n when d.drg_code between 582 and 585 then 1\n when d.drg_code between 597 and 599 then 1\n when d.drg_code between 656 and 658 then 1\n when d.drg_code between 686 and 688 then 1\n when d.drg_code between 715 and 716 then 1\n when d.drg_code between 722 and 724 then 1\n when d.drg_code between 736 and 741 then 1\n when d.drg_code between 754 and 756 then 1\n when d.drg_code between 826 and 830 then 1\n when d.drg_code between 843 and 849 then 1\nelse 0 end as cancdrg\n\n/* Connective tissue */\n, case\n when d.drg_code between 545 and 547 then 1\nelse 0 end as arthdrg\n\n/* Nutrition/metabolic */\n, case\n when d.drg_code between 640 and 641 then 1\nelse 0 end as nutrdrg\n\n/* Anemia */\n, case\n when d.drg_code between 808 and 812 then 1\nelse 0 end as anemdrg\n\n/* Alcohol drug */\n, case\n when d.drg_code between 894 and 897 then 1\nelse 0 end as alcdrg\n\n/*Coagulation disorders*/\n, case\n when d.drg_code = 813 then 1\nelse 0 end as coagdrg\n\n/*Hypertensive Complicated */\n, case\n when d.drg_code = 077 then 1\n when d.drg_code = 078 then 1\n when d.drg_code = 304 then 1\nelse 0 end as htncxdrg\n\n/*Hypertensive Uncomplicated */\n, case\n when d.drg_code = 079 then 1\n when d.drg_code = 305 then 1\nelse 0 end as htndrg\n\n/* Psychoses */\n, case\n when d.drg_code = 885 then 1\nelse 0 end as psydrg\n\n/* Obesity */\n, case\n when d.drg_code between 619 and 621 then 1\nelse 0 end as obesedrg\n\n/* Depressive Neuroses */\n, case\n when d.drg_code = 881 then 1\nelse 0 end as deprsdrg\n\nfrom\n(\n select hadm_id, drg_type, cast(drg_code as numeric) as drg_code\n from drgcodes\n where drg_type = 'MS'\n) d\n\n)\n, hcfadrg as\n(\nselect\n hadm_id\n\n /** V24 DRG Formats **/\n\n /* Cardiac */\n , case\n when d.drg_code between 103 and 112 then 1\n when d.drg_code between 115 and 118 then 1\n when d.drg_code between 121 and 127 then 1\n when d.drg_code = 129 then 1\n when d.drg_code = 132 then 1\n when d.drg_code = 133 then 1\n when d.drg_code between 135 and 143 then 1\n when d.drg_code between 514 and 518 then 1\n when d.drg_code between 525 and 527 then 1\n when d.drg_code between 535 and 536 then 1\n when d.drg_code between 547 and 550 then 1\n when d.drg_code between 551 and 558 then 1\n else 0 end as carddrg\n\n /* Peripheral vascular */\n ,
case\n when d.drg_code = 130 then 1\n when d.drg_code = 131 then 1\n else 0 end as peridrg\n\n /* Renal */\n , case\n when d.drg_code between 302 and 305 then 1\n when d.drg_code between 315 and 333 then 1\n\n else 0 end as renaldrg\n\n /* Nervous system */\n , case\n when d.drg_code between 1 and 35 then 1\n when d.drg_code = 524 then 1\n when d.drg_code between 528 and 534 then 1\n when d.drg_code = 543 then 1\n when d.drg_code between 559 and 564 then 1\n when d.drg_code = 577 then 1\n\n else 0 end as nervdrg\n\n /* Cerebrovascular */\n , case\n when d.drg_code = 5 then 1\n when d.drg_code between 14 and 17 then 1\n when d.drg_code = 524 then 1\n when d.drg_code = 528 then 1\n when d.drg_code between 533 and 534 then 1\n when d.drg_code = 577 then 1\n else 0 end as ceredrg\n\n /* COPD asthma */\n , case\n when d.drg_code = 88 then 1\n when d.drg_code between 96 and 98 then 1\n\n else 0 end as pulmdrg\n\n /* Diabetes */\n , case\n when d.drg_code = 294 then 1\n when d.drg_code = 295 then 1\n else 0 end as diabdrg\n\n /* Thyroid endocrine */\n , case\n when d.drg_code = 290 then 1\n when d.drg_code = 300 then 1\n when d.drg_code = 301 then 1\n\n else 0 end as hypodrg\n\n /* Kidney transp, renal fail/dialysis */\n , case\n when d.drg_code = 302 then 1\n when d.drg_code = 316 then 1\n when d.drg_code = 317 then 1\n else 0 end as renfdrg\n\n /* Liver */\n , case\n when d.drg_code between 199 and 202 then 1\n when d.drg_code between 205 and 208 then 1\n\n else 0 end as liverdrg\n\n /* GI hemorrhage or ulcer */\n , case\n when d.drg_code between 174 and 178 then 1\n else 0 end as ulcedrg\n\n /* Human immunodeficiency virus */\n , case\n when d.drg_code = 488 then 1\n when d.drg_code = 489 then 1\n when d.drg_code = 490 then 1\n\n else 0 end as hivdrg\n\n /* Leukemia/lymphoma */\n , case\n when d.drg_code between 400 and 414 then 1\n when d.drg_code = 473 then 1\n when d.drg_code = 492 then 1\n when d.drg_code between 539 and 540 then 1\n\n else 0 end as leukdrg\n\n /* Cancer, lymphoma */\n , case\n when d.drg_code = 10 then 1\n when d.drg_code = 11 then 1\n when d.drg_code = 64 then 1\n when d.drg_code = 82 then 1\n when d.drg_code = 172 then 1\n when d.drg_code = 173 then 1\n when d.drg_code = 199 then 1\n when d.drg_code = 203 then 1\n when d.drg_code = 239 then 1\n\n when d.drg_code between 257 and 260 then 1\n when d.drg_code = 274 then 1\n when d.drg_code = 275 then 1\n when d.drg_code = 303 then 1\n when d.drg_code = 318 then 1\n when d.drg_code = 319 then 1\n\n when d.drg_code = 338 then 1\n when d.drg_code = 344 then 1\n when d.drg_code = 346 then 1\n when d.drg_code = 347 then 1\n when d.drg_code = 354 then 1\n when d.drg_code = 355 then 1\n when d.drg_code = 357 then 1\n when d.drg_code = 363 then 1\n when d.drg_code = 366 then 1\n\n when d.drg_code = 367 then 1\n when d.drg_code between 406 and 414 then 1\n else 0 end as cancdrg\n\n /* Connective tissue */\n , case\n when d.drg_code = 240 then 1\n when d.drg_code = 241 then 1\n else 0 end as arthdrg\n\n /* Nutrition/metabolic */\n , case\n when d.drg_code between 296 and 298 then 1\n else 0 end as nutrdrg\n\n /* Anemia */\n ,
case\n when d.drg_code = 395 then 1\n when d.drg_code = 396 then 1\n when d.drg_code = 574 then 1\n else 0 end as anemdrg\n\n /* Alcohol drug */\n , case\n when d.drg_code between 433 and 437 then 1\n when d.drg_code between 521 and 523 then 1\n else 0 end as alcdrg\n\n /* Coagulation disorders */\n , case\n when d.drg_code = 397 then 1\n else 0 end as coagdrg\n\n /* Hypertensive Complicated */\n , case\n when d.drg_code = 22 then 1\n when d.drg_code = 134 then 1\n else 0 end as htncxdrg\n\n /* Hypertensive Uncomplicated */\n , case\n when d.drg_code = 134 then 1\n else 0 end as htndrg\n\n /* Psychoses */\n , case\n when d.drg_code = 430 then 1\n else 0 end as psydrg\n\n /* Obesity */\n , case\n when d.drg_code = 288 then 1\n else 0 end as obesedrg\n\n /* Depressive Neuroses */\n , case\n when d.drg_code = 426 then 1\n else 0 end as deprsdrg\n\n from\n (\n select hadm_id, drg_type, cast(drg_code as numeric) as drg_code\n from drgcodes\n where drg_type = 'HCFA'\n ) d\n)\n-- merge DRG groups together\n, drggrp as\n(\n select hadm_id\n, max(carddrg) as carddrg\n, max(peridrg) as peridrg\n, max(renaldrg) as renaldrg\n, max(nervdrg) as nervdrg\n, max(ceredrg) as ceredrg\n, max(pulmdrg) as pulmdrg\n, max(diabdrg) as diabdrg\n, max(hypodrg) as hypodrg\n, max(renfdrg) as renfdrg\n, max(liverdrg) as liverdrg\n, max(ulcedrg) as ulcedrg\n, max(hivdrg) as hivdrg\n, max(leukdrg) as leukdrg\n, max(cancdrg) as cancdrg\n, max(arthdrg) as arthdrg\n, max(nutrdrg) as nutrdrg\n, max(anemdrg) as anemdrg\n, max(alcdrg) as alcdrg\n, max(coagdrg) as coagdrg\n, max(htncxdrg) as htncxdrg\n, max(htndrg) as htndrg\n, max(psydrg) as psydrg\n, max(obesedrg) as obesedrg\n, max(deprsdrg) as deprsdrg\nfrom\n(\n select d1.* from msdrg d1\n UNION DISTINCT\n select d1.* from hcfadrg d1\n) d\ngroup by d.hadm_id\n)\n-- now merge these flags together to define elixhauser\n-- most are straightforward.. but hypertension flags are a bit more complicated\nselect adm.subject_id, adm.hadm_id\n, case\n when carddrg = 1 then 0 -- DRG filter\n\n when chf = 1 then 1\n when htnwchf = 1 then 1\n when hhrwchf = 1 then 1\n when hhrwhrf = 1 then 1\n else 0 end as congestive_heart_failure\n, case\n when carddrg = 1 then 0 -- DRG filter\n when arythm = 1 then 1\n else 0 end as cardiac_arrhythmias\n, case\n when carddrg = 1 then 0\n when valve = 1 then 1\n else 0 end as valvular_disease\n, case\n when carddrg = 1 or pulmdrg = 1 then 0\n when pulmcirc = 1 then 1\n else 0 end as pulmonary_circulation\n, case\n when peridrg = 1 then 0\n when perivasc = 1 then 1\n else 0 end as peripheral_vascular\n\n-- we combine 'htn' and 'htncx' into 'HYPERTENSION'\n-- note 'htn' (hypertension) is only 1 if 'htncx' (complicated hypertension) is 0\n-- also if htncxdrg = 1, then htndrg = 1\n\n-- In the original Sas code, it appears that:\n-- HTN can be 1\n-- HTNCX is set to 0 by DRGs\n-- but HTN_C is still 1, because HTN is 1\n-- so we have to do this complex addition.\n,\n
case\n when\n(\n-- first hypertension\ncase\n when htndrg = 0 then 0\n when htn = 1 then 1\nelse 0 end\n)\n+\n(\n-- next complicated hypertension\ncase\n when htncx = 1 and htncxdrg = 1 then 0\n\n when htnpreg = 1 and htncxdrg = 1 then 0\n when htnwochf = 1 and (htncxdrg = 1 OR carddrg = 1) then 0\n when htnwchf = 1 and htncxdrg = 1 then 0\n when htnwchf = 1 and carddrg = 1 then 0\n when hrenworf = 1 and (htncxdrg = 1 or renaldrg = 1) then 0\n when hrenwrf = 1 and htncxdrg = 1 then 0\n when hrenwrf = 1 and renaldrg = 1 then 0\n when hhrwohrf = 1 and (htncxdrg = 1 or carddrg = 1 or renaldrg = 1) then 0\n when hhrwchf = 1 and (htncxdrg = 1 or carddrg = 1 or renaldrg = 1) then 0\n when hhrwrf = 1 and (htncxdrg = 1 or carddrg = 1 or renaldrg = 1) then 0\n when hhrwhrf = 1 and (htncxdrg = 1 or carddrg = 1 or renaldrg = 1) then 0\n when ohtnpreg = 1 and (htncxdrg = 1 or carddrg = 1 or renaldrg = 1) then 0\n\n when htncx = 1 then 1\n when htnpreg = 1 then 1\n when htnwochf = 1 then 1\n when htnwchf = 1 then 1\n when hrenworf = 1 then 1\n when hrenwrf = 1 then 1\n when hhrwohrf = 1 then 1\n when hhrwchf = 1 then 1\n when hhrwrf = 1 then 1\n when hhrwhrf = 1 then 1\n when ohtnpreg = 1 then 1\n else 0 end\n)\n > 0 then 1 else 0 end as hypertension\n\n, case when ceredrg = 1 then 0 when para = 1 then 1 else 0 end as paralysis\n, case when nervdrg = 1 then 0 when neuro = 1 then 1 else 0 end as other_neurological\n, case when pulmdrg = 1 then 0 when chrnlung = 1 then 1 else 0 end as chronic_pulmonary\n, case\n -- only the more severe comorbidity (complicated diabetes) is kept\n when diabdrg = 1 then 0\n when dmcx = 1 then 0\n when dm = 1 then 1\n else 0 end as diabetes_uncomplicated\n, case when diabdrg = 1 then 0 when dmcx = 1 then 1 else 0 end as diabetes_complicated\n, case when hypodrg = 1 then 0 when hypothy = 1 then 1 else 0 end as hypothyroidism\n, case\n when renaldrg = 1 then 0\n when renlfail = 1 then 1\n when hrenwrf = 1 then 1\n when hhrwrf = 1 then 1\n when hhrwhrf = 1 then 1\n else 0 end as renal_failure\n\n, case when liverdrg = 1 then 0 when liver = 1 then 1 else 0 end as liver_disease\n, case when ulcedrg = 1 then 0 when ulcer = 1 then 1 else 0 end as peptic_ulcer\n, case when hivdrg = 1 then 0 when aids = 1 then 1 else 0 end as aids\n, case when leukdrg = 1 then 0 when lymph = 1 then 1 else 0 end as lymphoma\n, case when cancdrg = 1 then 0 when mets = 1 then 1 else 0 end as metastatic_cancer\n, case\n when cancdrg = 1 then 0\n -- only the more severe comorbidity (metastatic cancer) is kept\n when mets = 1 then 0\n when tumor = 1 then 1\n else 0 end as solid_tumor\n, case when arthdrg = 1 then 0 when arth = 1 then 1 else 0 end as rheumatoid_arthritis\n, case when coagdrg = 1 then 0 when coag = 1 then 1 else 0 end as coagulopathy\n, case when nutrdrg = 1\n OR obesedrg = 1 then 0 when obese = 1 then 1 else 0 end as obesity\n, case when nutrdrg = 1 then 0 when wghtloss = 1 then 1 else 0 end as weight_loss\n, case when nutrdrg = 1 then 0 when lytes = 1 then 1 else 0 end as fluid_electrolyte\n, case when anemdrg = 1 then 0 when bldloss = 1 then 1 else 0 end as blood_loss_anemia\n, case when anemdrg = 1 then 0 when anemdef = 1 then 1 else 0 end as deficiency_anemias\n, case when alcdrg = 1 then 0 when alcohol = 1 then 1 else 0 end as alcohol_abuse\n, case when alcdrg = 1 then 0 when drug = 1 then 1 else 0 end as drug_abuse\n, case when psydrg = 1 then 0 when psych = 1 then 1 else 0 end as psychoses\n, case when deprsdrg = 1 then 0 when depress = 1 then 1 else 0 end as depression\n\n\nFROM admissions adm\nleft join eligrp eli\n on adm.hadm_id = eli.hadm_id\nleft join drggrp d\n on adm.hadm_id = d.hadm_id\norder by adm.hadm_id;\n-- jing add tail\nalter table mimic3.comorbidity_elixhauser_ahrq_v37\nowner to postgres;\n"
elixhauser_ahrq_v37_no_drg <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS comorbidity_elixhauser_ahrq_v37_no_drg;\ncreate materialized view mimic3.comorbidity_elixhauser_ahrq_v37_no_drg\ntablespace pg_default\nas\n-- jing add head\n-- This code uses the latest version of Elixhauser provided by AHRQ\n-- However, it does *not* filter based on diagnosis related groups (DRGs)\n-- As such, \"comorbidities\" identified are more likely to be associated with the primary reason for their hospital stay\n\n-- The code:\n -- removes \"primary\" ICD9_CODE (seq_num != 1)\n-- uses AHRQ published rules to define comorbidities\nwith\neliflg as\n(\n select hadm_id, seq_num, icd9_code\n -- note that these codes will seem incomplete at first\n -- for example, CHF is missing a lot of codes referenced in the literature (402.11, 402.91, etc)\n -- these codes are captured by hypertension flags instead\n -- later there are some complicated rules which confirm/reject those codes as chf\n , CASE\n when icd9_code = '39891' then 1\n when icd9_code between '4280' and '4289' then 1\n end as chf /* Congestive heart failure */\n \n -- cardiac arrhythmias is removed in up to date versions\n , case\n when icd9_code = '42610' then 1\n when icd9_code = '42611' then 1\n when icd9_code = '42613' then 1\n when icd9_code between '4262' and '42653' then 1\n when icd9_code between '4266' and '42689' then 1\n when icd9_code = '4270' then 1\n when icd9_code = '4272' then 1\n when icd9_code = '42731' then 1\n when icd9_code = '42760' then 1\n when icd9_code = '4279' then 1\n when icd9_code = '7850' then 1\n when icd9_code between 'V450' and 'V4509' then 1\n when icd9_code between 'V533' and 'V5339' then 1\n end as arythm /* Cardiac arrhythmias */\n \n , CASE\n when icd9_code between '09320' and '09324' then 1\n when icd9_code between '3940' and '3971' then 1\n when icd9_code = '3979' then 1\n when icd9_code between '4240' and '42499' then 1\n when icd9_code between '7463' and '7466' then 1\n when icd9_code = 'V422' then 1\n when icd9_code = 'V433' then 1\n end as valve /* Valvular disease */\n \n , CASE\n when icd9_code between '41511' and '41519' then 1\n when icd9_code between '4160' and '4169' then 1\n when icd9_code = '4179' then 1\n end as pulmcirc /* Pulmonary circulation disorder */\n \n , CASE\n when icd9_code between '4400' and '4409' then 1\n when icd9_code between '44100' and '4419' then 1\n when icd9_code between '4420' and '4429' then 1\n when icd9_code between '4431' and '4439' then 1\n when icd9_code between '44421' and '44422' then 1\n when icd9_code = '4471' then 1\n when icd9_code = '449' then 1\n when icd9_code = '5571' then 1\n when icd9_code = '5579' then 1\n when icd9_code = 'V434' then 1\n end as perivasc /* Peripheral vascular disorder */\n \n ,
CASE\n when icd9_code = '4011' then 1\n when icd9_code = '4019' then 1\n when icd9_code between '64200' and '64204' then 1\n end as htn /* Hypertension, uncomplicated */\n \n , CASE\n when icd9_code = '4010' then 1\n when icd9_code = '4372' then 1\n end as htncx /* Hypertension, complicated */\n \n \n /******************************************************************/\n /* The following are special, temporary formats used in the */\n /* creation of the hypertension complicated comorbidity when */\n /* overlapping with congestive heart failure or renal failure */\n /* occurs. These temporary formats are referenced in the program */\n /* called comoanaly2009.txt. */\n /******************************************************************/\n , CASE\n when icd9_code between '64220' and '64224' then 1\n end as htnpreg /* Pre-existing hypertension complicating pregnancy */\n \n , CASE\n when icd9_code = '40200' then 1\n when icd9_code = '40210' then 1\n when icd9_code = '40290' then 1\n when icd9_code = '40509' then 1\n when icd9_code = '40519' then 1\n when icd9_code = '40599' then 1\n end as htnwochf /* Hypertensive heart disease without heart failure */\n \n , CASE\n when icd9_code = '40201' then 1\n when icd9_code = '40211' then 1\n when icd9_code = '40291' then 1\n end as htnwchf /* Hypertensive heart disease with heart failure */\n \n , CASE\n when icd9_code = '40300' then 1\n when icd9_code = '40310' then 1\n when icd9_code = '40390' then 1\n when icd9_code = '40501' then 1\n when icd9_code = '40511' then 1\n when icd9_code = '40591' then 1\n when icd9_code between '64210' and '64214' then 1\n end as hrenworf /* Hypertensive renal disease without renal failure */\n \n , CASE\n when icd9_code = '40301' then 1\n when icd9_code = '40311' then 1\n when icd9_code = '40391' then 1\n end as hrenwrf /* Hypertensive renal disease with renal failure */\n \n , CASE\n when icd9_code = '40400' then 1\n when icd9_code = '40410' then 1\n when icd9_code = '40490' then 1\n end as hhrwohrf /* Hypertensive heart and renal disease without heart or renal failure */\n \n , CASE\n when icd9_code = '40401' then 1\n when icd9_code = '40411' then 1\n when icd9_code = '40491' then 1\n end as hhrwchf /* Hypertensive heart and renal disease with heart failure */\n \n , CASE\n when icd9_code = '40402' then 1\n when icd9_code = '40412' then 1\n when icd9_code = '40492' then 1\n end as hhrwrf /* Hypertensive heart and renal disease with renal failure */\n \n , CASE\n when icd9_code = '40403' then 1\n when icd9_code = '40413' then 1\n when icd9_code = '40493' then 1\n end as hhrwhrf /* Hypertensive heart and renal disease with heart and renal failure */\n \n ,
CASE\n when icd9_code between '64270' and '64274' then 1\n when icd9_code between '64290' and '64294' then 1\n end as ohtnpreg /* Other hypertension in pregnancy */\n \n /******************** End temporary Formats ***********************/\n \n , CASE\n when icd9_code between '3420' and '3449' then 1\n when icd9_code between '43820' and '43853' then 1\n when icd9_code = '78072' then 1\n end as para /* Paralysis */\n \n , CASE\n when icd9_code between '3300' and '3319' then 1\n when icd9_code = '3320' then 1\n when icd9_code = '3334' then 1\n when icd9_code = '3335' then 1\n when icd9_code = '3337' then 1\n when icd9_code in ('33371','33372','33379','33385','33394') then 1\n when icd9_code between '3340' and '3359' then 1\n when icd9_code = '3380' then 1\n when icd9_code = '340' then 1\n when icd9_code between '3411' and '3419' then 1\n when icd9_code between '34500' and '34511' then 1\n when icd9_code between '3452' and '3453' then 1\n when icd9_code between '34540' and '34591' then 1\n when icd9_code between '34700' and '34701' then 1\n when icd9_code between '34710' and '34711' then 1\n when icd9_code = '3483' then 1 -- discontinued icd-9\n when icd9_code between '64940' and '64944' then 1\n when icd9_code = '7687' then 1\n when icd9_code between '76870' and '76873' then 1\n when icd9_code = '7803' then 1\n when icd9_code = '78031' then 1\n when icd9_code = '78032' then 1\n when icd9_code = '78033' then 1\n when icd9_code = '78039' then 1\n when icd9_code = '78097' then 1\n when icd9_code = '7843' then 1\n end as neuro /* Other neurological */\n \n , CASE\n when icd9_code between '490' and '4928' then 1\n when icd9_code between '49300' and '49392' then 1\n when icd9_code between '494' and '4941' then 1\n when icd9_code between '4950' and '505' then 1\n when icd9_code = '5064' then 1\n end as chrnlung /* Chronic pulmonary disease */\n \n , CASE\n when icd9_code between '25000' and '25033' then 1\n when icd9_code between '64800' and '64804' then 1\n when icd9_code between '24900' and '24931' then 1\n end as dm /* Diabetes w/o chronic complications*/\n \n , CASE\n when icd9_code between '25040' and '25093' then 1\n when icd9_code = '7751' then 1\n when icd9_code between '24940' and '24991' then 1\n end as dmcx /* Diabetes w/ chronic complications */\n \n , CASE\n when icd9_code between '243' and '2442' then 1\n when icd9_code = '2448' then 1\n when icd9_code = '2449' then 1\n end as hypothy /* Hypothyroidism */\n \n , CASE\n when icd9_code = '585' then 1 -- discontinued code\n when icd9_code = '5853' then 1\n when icd9_code = '5854' then 1\n when icd9_code = '5855' then 1\n when icd9_code = '5856' then 1\n when icd9_code = '5859' then 1\n when icd9_code = '586' then 1\n when icd9_code = 'V420' then 1\n when icd9_code = 'V451' then 1\n when icd9_code between 'V560' and 'V5632' then 1\n when icd9_code = 'V568' then 1\n when icd9_code between 'V4511' and 'V4512' then 1\n end as renlfail /* Renal failure */\n \n ,
CASE\n when icd9_code = '07022' then 1\n when icd9_code = '07023' then 1\n when icd9_code = '07032' then 1\n when icd9_code = '07033' then 1\n when icd9_code = '07044' then 1\n when icd9_code = '07054' then 1\n when icd9_code = '4560' then 1\n when icd9_code = '4561' then 1\n when icd9_code = '45620' then 1\n when icd9_code = '45621' then 1\n when icd9_code = '5710' then 1\n when icd9_code = '5712' then 1\n when icd9_code = '5713' then 1\n when icd9_code between '57140' and '57149' then 1\n when icd9_code = '5715' then 1\n when icd9_code = '5716' then 1\n when icd9_code = '5718' then 1\n when icd9_code = '5719' then 1\n when icd9_code = '5723' then 1\n when icd9_code = '5728' then 1\n when icd9_code = '5735' then 1\n when icd9_code = 'V427' then 1\n end as liver /* Liver disease */\n \n , CASE\n when icd9_code = '53141' then 1\n when icd9_code = '53151' then 1\n when icd9_code = '53161' then 1\n when icd9_code = '53170' then 1\n when icd9_code = '53171' then 1\n when icd9_code = '53191' then 1\n when icd9_code = '53241' then 1\n when icd9_code = '53251' then 1\n when icd9_code = '53261' then 1\n when icd9_code = '53270' then 1\n when icd9_code = '53271' then 1\n when icd9_code = '53291' then 1\n when icd9_code = '53341' then 1\n when icd9_code = '53351' then 1\n when icd9_code = '53361' then 1\n when icd9_code = '53370' then 1\n when icd9_code = '53371' then 1\n when icd9_code = '53391' then 1\n when icd9_code = '53441' then 1\n when icd9_code = '53451' then 1\n when icd9_code = '53461' then 1\n when icd9_code = '53470' then 1\n when icd9_code = '53471' then 1\n when icd9_code = '53491' then 1\n end as ulcer /* Chronic Peptic ulcer disease (includes bleeding only if obstruction is also present) */\n \n , CASE\n when icd9_code between '042' and '0449' then 1\n end as aids /* HIV and AIDS */\n \n , CASE\n when icd9_code between '20000' and '20238' then 1\n when icd9_code between '20250' and '20301' then 1\n when icd9_code = '2386' then 1\n when icd9_code = '2733' then 1\n when icd9_code between '20302' and '20382' then 1\n end as lymph /* Lymphoma */\n \n , CASE\n when icd9_code between '1960' and '1991' then 1\n when icd9_code between '20970' and '20975' then 1\n when icd9_code = '20979' then 1\n when icd9_code = '78951' then 1\n end as mets /* Metastatic cancer */\n \n , CASE\n when icd9_code between '1400' and '1729' then 1\n when icd9_code between '1740' and '1759' then 1\n when icd9_code between '179' and '1958' then 1\n when icd9_code between '20900' and '20924' then 1\n when icd9_code between '20925' and '2093' then 1\n when icd9_code between '20930' and '20936' then 1\n when icd9_code between '25801' and '25803' then 1\n end as tumor /* Solid tumor without metastasis */\n \n ,
CASE\n when icd9_code = '7010' then 1\n when icd9_code between '7100' and '7109' then 1\n when icd9_code between '7140' and '7149' then 1\n when icd9_code between '7200' and '7209' then 1\n when icd9_code = '725' then 1\n end as arth /* Rheumatoid arthritis/collagen vascular diseases */\n \n , CASE\n when icd9_code between '2860' and '2869' then 1\n when icd9_code = '2871' then 1\n when icd9_code between '2873' and '2875' then 1\n when icd9_code between '64930' and '64934' then 1\n when icd9_code = '28984' then 1\n end as coag /* Coagulation deficiency */\n \n , CASE\n when icd9_code = '2780' then 1\n when icd9_code = '27800' then 1\n when icd9_code = '27801' then 1\n when icd9_code = '27803' then 1\n when icd9_code between '64910' and '64914' then 1\n when icd9_code between 'V8530' and 'V8539' then 1\n when icd9_code = 'V854' then 1 -- hierarchy used for AHRQ v3.6 and earlier\n when icd9_code between 'V8541' and 'V8545' then 1\n when icd9_code = 'V8554' then 1\n when icd9_code = '79391' then 1\n end as obese /* Obesity */\n \n , CASE\n when icd9_code between '260' and '2639' then 1\n when icd9_code between '78321' and '78322' then 1\n end as wghtloss /* Weight loss */\n \n , CASE\n when icd9_code between '2760' and '2769' then 1\n end as lytes /* Fluid and electrolyte disorders - note:\n this comorbidity should be dropped when\n used with the AHRQ Patient Safety Indicators*/\n , CASE\n when icd9_code = '2800' then 1\n when icd9_code between '64820' and '64824' then 1\n end as bldloss /* Blood loss anemia */\n \n , CASE\n when icd9_code between '2801' and '2819' then 1\n when icd9_code between '28521' and '28529' then 1\n when icd9_code = '2859' then 1\n end as anemdef /* Deficiency anemias */\n \n , CASE\n when icd9_code between '2910' and '2913' then 1\n when icd9_code = '2915' then 1\n when icd9_code = '2918' then 1\n when icd9_code = '29181' then 1\n when icd9_code = '29182' then 1\n when icd9_code = '29189' then 1\n when icd9_code = '2919' then 1\n when icd9_code between '30300' and '30393' then 1\n when icd9_code between '30500' and '30503' then 1\n end as alcohol /* Alcohol abuse */\n \n , CASE\n when icd9_code = '2920' then 1\n when icd9_code between '29282' and '29289' then 1\n when icd9_code = '2929' then 1\n when icd9_code between '30400' and '30493' then 1\n when icd9_code between '30520' and '30593' then 1\n when icd9_code between '64830' and '64834' then 1\n end as drug /* Drug abuse */\n \n , CASE\n when icd9_code between '29500' and '2989' then 1\n when icd9_code = '29910' then 1\n when icd9_code = '29911' then 1\n end as psych /* Psychoses */\n \n ,
CASE\n when icd9_code = '3004' then 1\n when icd9_code = '30112' then 1\n when icd9_code = '3090' then 1\n when icd9_code = '3091' then 1\n when icd9_code = '311' then 1\n end as depress /* Depression */\n from diagnoses_icd icd\n WHERE seq_num = 1\n)\n-- collapse the icd9_code specific flags into hadm_id specific flags\n-- this groups comorbidities together for a single patient admission\n, eligrp as\n(\n select hadm_id\n , max(chf) as chf\n , max(arythm) as arythm\n , max(valve) as valve\n , max(pulmcirc) as pulmcirc\n , max(perivasc) as perivasc\n , max(htn) as htn\n , max(htncx) as htncx\n , max(htnpreg) as htnpreg\n , max(htnwochf) as htnwochf\n , max(htnwchf) as htnwchf\n , max(hrenworf) as hrenworf\n , max(hrenwrf) as hrenwrf\n , max(hhrwohrf) as hhrwohrf\n , max(hhrwchf) as hhrwchf\n , max(hhrwrf) as hhrwrf\n , max(hhrwhrf) as hhrwhrf\n , max(ohtnpreg) as ohtnpreg\n , max(para) as para\n , max(neuro) as neuro\n , max(chrnlung) as chrnlung\n , max(dm) as dm\n , max(dmcx) as dmcx\n , max(hypothy) as hypothy\n , max(renlfail) as renlfail\n , max(liver) as liver\n , max(ulcer) as ulcer\n , max(aids) as aids\n , max(lymph) as lymph\n , max(mets) as mets\n , max(tumor) as tumor\n , max(arth) as arth\n , max(coag) as coag\n , max(obese) as obese\n , max(wghtloss) as wghtloss\n , max(lytes) as lytes\n , max(bldloss) as bldloss\n , max(anemdef) as anemdef\n , max(alcohol) as alcohol\n , max(drug) as drug\n , max(psych) as psych\n , max(depress) as depress\n from eliflg\n group by hadm_id\n)\n-- now merge these flags together to define elixhauser\n-- most are straightforward.. but hypertension flags are a bit more complicated\nselect adm.subject_id, adm.hadm_id\n, case\nwhen chf = 1 then 1\nwhen htnwchf = 1 then 1\nwhen hhrwchf = 1 then 1\nwhen hhrwhrf = 1 then 1\nelse 0 end as congestive_heart_failure\n, case\nwhen arythm = 1 then 1\nelse 0 end as cardiac_arrhythmias\n, case when valve = 1 then 1 else 0 end as valvular_disease\n, case when pulmcirc = 1 then 1 else 0 end as pulmonary_circulation\n, case when perivasc = 1 then 1 else 0 end as peripheral_vascular\n\n-- we combine \"htn\" and \"htncx\" into \"HYPERTENSION\"\n-- note \"htn\" (hypertension) is only 1 if \"htncx\" (complicated hypertension) is 0\n-- this matters if you filter on DRG but for this query we can just merge them immediately\n, case\nwhen htn = 1 then 1\nwhen htncx = 1 then 1\nwhen htnpreg = 1 then 1\nwhen htnwochf = 1 then 1\nwhen htnwchf = 1 then 1\nwhen hrenworf = 1 then 1\nwhen hrenwrf = 1 then 1\nwhen hhrwohrf = 1 then 1\nwhen hhrwchf = 1 then 1\nwhen hhrwrf = 1 then 1\nwhen hhrwhrf = 1 then 1\nwhen ohtnpreg = 1 then 1\nelse 0 end as hypertension\n\n, case when para = 1 then 1 else 0 end as paralysis\n, case when neuro = 1 then 1 else 0 end as other_neurological\n, case when chrnlung = 1 then 1 else 0 end as chronic_pulmonary\n,
case\n-- only the more severe comorbidity (complicated diabetes) is kept\nwhen dmcx = 1 then 0\nwhen dm = 1 then 1\nelse 0 end as diabetes_uncomplicated\n, case when dmcx = 1 then 1 else 0 end as diabetes_complicated\n, case when hypothy = 1 then 1 else 0 end as hypothyroidism\n, case\nwhen renlfail = 1 then 1\nwhen hrenwrf = 1 then 1\nwhen hhrwrf = 1 then 1\nwhen hhrwhrf = 1 then 1\nelse 0 end as renal_failure\n\n, case when liver = 1 then 1 else 0 end as liver_disease\n, case when ulcer = 1 then 1 else 0 end as peptic_ulcer\n, case when aids = 1 then 1 else 0 end as aids\n, case when lymph = 1 then 1 else 0 end as lymphoma\n, case when mets = 1 then 1 else 0 end as metastatic_cancer\n, case\n-- only the more severe comorbidity (metastatic cancer) is kept\nwhen mets = 1 then 0\nwhen tumor = 1 then 1\nelse 0 end as solid_tumor\n, case when arth = 1 then 1 else 0 end as rheumatoid_arthritis\n, case when coag = 1 then 1 else 0 end as coagulopathy\n, case when obese = 1 then 1 else 0 end as obesity\n, case when wghtloss = 1 then 1 else 0 end as weight_loss\n, case when lytes = 1 then 1 else 0 end as fluid_electrolyte\n, case when bldloss = 1 then 1 else 0 end as blood_loss_anemia\n, case when anemdef = 1 then 1 else 0 end as deficiency_anemias\n, case when alcohol = 1 then 1 else 0 end as alcohol_abuse\n, case when drug = 1 then 1 else 0 end as drug_abuse\n, case when psych = 1 then 1 else 0 end as psychoses\n, case when depress = 1 then 1 else 0 end as depression\n\nFROM admissions adm\nleft join eligrp eli\non adm.hadm_id = eli.hadm_id\norder by adm.hadm_id;\n-- jing add tail\nalter table mimic3.comorbidity_elixhauser_ahrq_v37_no_drg\nowner to postgres;\n"
elixhauser_quan <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS comorbidity_elixhauser_quan;\ncreate materialized view mimic3.comorbidity_elixhauser_quan\ntablespace pg_default\nas\n-- jing add head\n-- This code calculates the Elixhauser comorbidities as defined in Quan et. al 2009:\n -- Quan, Hude, et al. \"Coding algorithms for defining comorbidities in\n-- ICD-9-CM and ICD-10 administrative data.\" Medical care (2005): 1130-1139.\n-- https://www.ncbi.nlm.nih.gov/pubmed/16224307\n\n-- Quan defined an \"Enhanced ICD-9\" coding scheme for deriving Elixhauser\n-- comorbidities from ICD-9 billing codes. This script implements that calculation.\n\n-- The logic of the code is roughly that, if the comorbidity lists a length 3\n-- ICD-9 code (e.g. 585), then we only require a match on the first 3 characters.\n\n-- This code derives each comorbidity as follows:\n -- 1) ICD9_CODE is directly compared to 5 character codes\n-- 2) The first 4 characters of ICD9_CODE are compared to 4 character codes\n-- 3) The first 3 characters of ICD9_CODE are compared to 3 character codes\nwith eliflg as\n(\n select hadm_id, seq_num, icd9_code\n , CASE\n when icd9_code in ('39891','40201','40211','40291','40401','40403','40411','40413','40491','40493') then 1\n when SUBSTR(icd9_code, 1, 4) in ('4254','4255','4257','4258','4259') then 1\n when SUBSTR(icd9_code, 1, 3) in ('428') then 1\n else 0 end as chf /* Congestive heart failure */\n \n , CASE\n when icd9_code in ('42613','42610','42612','99601','99604') then 1\n when SUBSTR(icd9_code, 1, 4) in ('4260','4267','4269','4270','4271','4272','4273','4274','4276','4278','4279','7850','V450','V533') then 1\n else 0 end as arrhy\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('0932','7463','7464','7465','7466','V422','V433') then 1\n when SUBSTR(icd9_code, 1, 3) in ('394','395','396','397','424') then 1\n else 0 end as valve /* Valvular disease */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('4150','4151','4170','4178','4179') then 1\n when SUBSTR(icd9_code, 1, 3) in ('416') then 1\n else 0 end as pulmcirc /* Pulmonary circulation disorder */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('0930','4373','4431','4432','4438','4439','4471','5571','5579','V434') then 1\n when SUBSTR(icd9_code, 1, 3) in ('440','441') then 1\n else 0 end as perivasc /* Peripheral vascular disorder */\n \n , CASE\n when SUBSTR(icd9_code, 1, 3) in ('401') then 1\n else 0 end as htn /* Hypertension, uncomplicated */\n \n , CASE\n when SUBSTR(icd9_code, 1, 3) in ('402','403','404','405') then 1\n else 0 end as htncx /* Hypertension, complicated */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('3341','3440','3441','3442','3443','3444','3445','3446','3449') then 1\n when SUBSTR(icd9_code, 1, 3) in ('342','343') then 1\n else 0 end as para /* Paralysis */\n \n ,
CASE\n when icd9_code in ('33392') then 1\n when SUBSTR(icd9_code, 1, 4) in ('3319','3320','3321','3334','3335','3362','3481','3483','7803','7843') then 1\n when SUBSTR(icd9_code, 1, 3) in ('334','335','340','341','345') then 1\n else 0 end as neuro /* Other neurological */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('4168','4169','5064','5081','5088') then 1\n when SUBSTR(icd9_code, 1, 3) in ('490','491','492','493','494','495','496','500','501','502','503','504','505') then 1\n else 0 end as chrnlung /* Chronic pulmonary disease */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2500','2501','2502','2503') then 1\n else 0 end as dm /* Diabetes w/o chronic complications*/\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2504','2505','2506','2507','2508','2509') then 1\n else 0 end as dmcx /* Diabetes w/ chronic complications */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2409','2461','2468') then 1\n when SUBSTR(icd9_code, 1, 3) in ('243','244') then 1\n else 0 end as hypothy /* Hypothyroidism */\n \n , CASE\n when icd9_code in ('40301','40311','40391','40402','40403','40412','40413','40492','40493') then 1\n when SUBSTR(icd9_code, 1, 4) in ('5880','V420','V451') then 1\n when SUBSTR(icd9_code, 1, 3) in ('585','586','V56') then 1\n else 0 end as renlfail /* Renal failure */\n \n , CASE\n when icd9_code in ('07022','07023','07032','07033','07044','07054') then 1\n when SUBSTR(icd9_code, 1, 4) in ('0706','0709','4560','4561','4562','5722','5723','5724','5728','5733','5734','5738','5739','V427') then 1\n when SUBSTR(icd9_code, 1, 3) in ('570','571') then 1\n else 0 end as liver /* Liver disease */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('5317','5319','5327','5329','5337','5339','5347','5349') then 1\n else 0 end as ulcer /* Chronic Peptic ulcer disease (includes bleeding only if obstruction is also present) */\n \n , CASE\n when SUBSTR(icd9_code, 1, 3) in ('042','043','044') then 1\n else 0 end as aids /* HIV and AIDS */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2030','2386') then 1\n when SUBSTR(icd9_code, 1, 3) in ('200','201','202') then 1\n else 0 end as lymph /* Lymphoma */\n \n , CASE\n when SUBSTR(icd9_code, 1, 3) in ('196','197','198','199') then 1\n else 0 end as mets /* Metastatic cancer */\n \n , CASE\n when SUBSTR(icd9_code, 1, 3) in\n (\n '140','141','142','143','144','145','146','147','148','149','150','151','152'\n ,'153','154','155','156','157','158','159','160','161','162','163','164','165'\n ,'166','167','168','169','170','171','172','174','175','176','177','178','179'\n ,'180','181','182','183','184','185','186','187','188','189','190','191','192'\n ,'193','194','195'\n ) then 1\n else 0 end as tumor /* Solid tumor without metastasis */\n \n , CASE\n when icd9_code in ('72889','72930') then 1\n when SUBSTR(icd9_code, 1, 4) in ('7010','7100','7101','7102','7103','7104','7108','7109','7112','7193','7285') then 1\n when SUBSTR(icd9_code, 1, 3) in ('446','714','720','725') then 1\n else 0 end as arth /* Rheumatoid arthritis/collagen vascular diseases */\n \n ,
CASE\n when SUBSTR(icd9_code, 1, 4) in ('2871','2873','2874','2875') then 1\n when SUBSTR(icd9_code, 1, 3) in ('286') then 1\n else 0 end as coag /* Coagulation deficiency */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2780') then 1\n else 0 end as obese /* Obesity */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('7832','7994') then 1\n when SUBSTR(icd9_code, 1, 3) in ('260','261','262','263') then 1\n else 0 end as wghtloss /* Weight loss */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2536') then 1\n when SUBSTR(icd9_code, 1, 3) in ('276') then 1\n else 0 end as lytes /* Fluid and electrolyte disorders */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2800') then 1\n else 0 end as bldloss /* Blood loss anemia */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2801','2808','2809') then 1\n when SUBSTR(icd9_code, 1, 3) in ('281') then 1\n else 0 end as anemdef /* Deficiency anemias */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2652','2911','2912','2913','2915','2918','2919','3030','3039','3050','3575','4255','5353','5710','5711','5712','5713','V113') then 1\n when SUBSTR(icd9_code, 1, 3) in ('980') then 1\n else 0 end as alcohol /* Alcohol abuse */\n \n , CASE\n when icd9_code in ('V6542') then 1\n when SUBSTR(icd9_code, 1, 4) in ('3052','3053','3054','3055','3056','3057','3058','3059') then 1\n when SUBSTR(icd9_code, 1, 3) in ('292','304') then 1\n else 0 end as drug /* Drug abuse */\n \n , CASE\n when icd9_code in ('29604','29614','29644','29654') then 1\n when SUBSTR(icd9_code, 1, 4) in ('2938') then 1\n when SUBSTR(icd9_code, 1, 3) in ('295','297','298') then 1\n else 0 end as psych /* Psychoses */\n \n , CASE\n when SUBSTR(icd9_code, 1, 4) in ('2962','2963','2965','3004') then 1\n when SUBSTR(icd9_code, 1, 3) in ('309','311') then 1\n else 0 end as depress /* Depression */\n from diagnoses_icd icd\n where seq_num != 1 -- we do not include the primary icd-9 code\n)\n-- collapse the icd9_code specific flags into hadm_id specific flags\n-- this groups comorbidities together for a single patient admission\n, eligrp as\n(\n select hadm_id\n , max(chf) as chf\n , max(arrhy) as arrhy\n , max(valve) as valve\n , max(pulmcirc) as pulmcirc\n , max(perivasc) as perivasc\n , max(htn) as htn\n , max(htncx) as htncx\n , max(para) as para\n , max(neuro) as neuro\n , max(chrnlung) as chrnlung\n , max(dm) as dm\n , max(dmcx) as dmcx\n , max(hypothy) as hypothy\n , max(renlfail) as renlfail\n , max(liver) as liver\n , max(ulcer) as ulcer\n , max(aids) as aids\n , max(lymph) as lymph\n , max(mets) as mets\n , max(tumor) as tumor\n , max(arth) as arth\n , max(coag) as coag\n , max(obese) as obese\n , max(wghtloss) as wghtloss\n , max(lytes) as lytes\n , max(bldloss) as bldloss\n , max(anemdef) as anemdef\n , max(alcohol) as alcohol\n , max(drug) as drug\n , max(psych) as psych\n , max(depress) as depress\n from eliflg\n group by hadm_id\n)\n-- now merge these flags together to define elixhauser\n-- most are straightforward.. but hypertension flags are a bit more complicated\n\n\nselect adm.hadm_id\n, chf as congestive_heart_failure\n, arrhy as cardiac_arrhythmias\n, valve as valvular_disease\n, pulmcirc as pulmonary_circulation\n, perivasc as peripheral_vascular\n-- we combine \"htn\" and \"htncx\" into \"HYPERTENSION\"\n,
case\nwhen htn = 1 then 1\nwhen htncx = 1 then 1\nelse 0 end as hypertension\n, para as paralysis\n, neuro as other_neurological\n, chrnlung as chronic_pulmonary\n-- only the more severe comorbidity (complicated diabetes) is kept\n, case\nwhen dmcx = 1 then 0\nwhen dm = 1 then 1\nelse 0 end as diabetes_uncomplicated\n, dmcx as diabetes_complicated\n, hypothy as hypothyroidism\n, renlfail as renal_failure\n, liver as liver_disease\n, ulcer as peptic_ulcer\n, aids as aids\n, lymph as lymphoma\n, mets as metastatic_cancer\n-- only the more severe comorbidity (metastatic cancer) is kept\n, case\nwhen mets = 1 then 0\nwhen tumor = 1 then 1\nelse 0 end as solid_tumor\n, arth as rheumatoid_arthritis\n, coag as coagulopathy\n, obese as obesity\n, wghtloss as weight_loss\n, lytes as fluid_electrolyte\n, bldloss as blood_loss_anemia\n, anemdef as deficiency_anemias\n, alcohol as alcohol_abuse\n, drug as drug_abuse\n, psych as psychoses\n, depress as depression\n\nFROM admissions adm\nleft join eligrp eli\non adm.hadm_id = eli.hadm_id\norder by adm.hadm_id;\n-- jing add tail\nalter table mimic3.comorbidity_elixhauser_quan\nowner to postgres;\n"
elixhauser_score_ahrq <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS comorbidity_elixhauser_score_ahrq;\ncreate materialized view mimic3.comorbidity_elixhauser_score_ahrq\ntablespace pg_default\nas\n-- jing add head\n-- This query provides various methods of combining the Elixhauser components into a single score\n-- The methods are called \"vanWalRaven\" and \"SID30\", and \"SID29\"\nselect subject_id, hadm_id\n, -- Below is the van Walraven score\n0 * aids +\n 0 * alcohol_abuse +\n -2 * blood_loss_anemia +\n 7 * congestive_heart_failure +\n -- Cardiac arrhythmias are not included in van Walraven based on Quan 2007\n3 * chronic_pulmonary +\n 3 * coagulopathy +\n -2 * deficiency_anemias +\n -3 * depression +\n 0 * diabetes_complicated +\n 0 * diabetes_uncomplicated +\n -7 * drug_abuse +\n 5 * fluid_electrolyte +\n 0 * hypertension +\n 0 * hypothyroidism +\n 11 * liver_disease +\n 9 * lymphoma +\n 12 * metastatic_cancer +\n 6 * other_neurological +\n -4 * obesity +\n 7 * paralysis +\n 2 * peripheral_vascular +\n 0 * peptic_ulcer +\n 0 * psychoses +\n 4 * pulmonary_circulation +\n 0 * rheumatoid_arthritis +\n 5 * renal_failure +\n 4 * solid_tumor +\n -1 * valvular_disease +\n 6 * weight_loss\nas elixhauser_vanwalraven\n\n\n\n, -- Below is the 29 component SID score\n0 * aids +\n -2 * alcohol_abuse +\n -2 * blood_loss_anemia +\n -- Cardiac arrhythmias are not included in SID-29\n9 * congestive_heart_failure +\n 3 * chronic_pulmonary +\n 9 * coagulopathy +\n 0 * deficiency_anemias +\n -4 * depression +\n 0 * diabetes_complicated +\n -1 * diabetes_uncomplicated +\n -8 * drug_abuse +\n 9 * fluid_electrolyte +\n -1 * hypertension +\n 0 * hypothyroidism +\n 5 * liver_disease +\n 6 * lymphoma +\n 13 * metastatic_cancer +\n 4 * other_neurological +\n -4 * obesity +\n 3 * paralysis +\n 0 * peptic_ulcer +\n 4 * peripheral_vascular +\n -4 * psychoses +\n 5 * pulmonary_circulation +\n 6 * renal_failure +\n 0 * rheumatoid_arthritis +\n 8 * solid_tumor +\n 0 * valvular_disease +\n 8 * weight_loss\nas elixhauser_SID29\n\n\n, -- Below is the 30 component SID score\n0 * aids +\n 0 * alcohol_abuse +\n -3 * blood_loss_anemia +\n 8 * cardiac_arrhythmias +\n 9 * congestive_heart_failure +\n 3 * chronic_pulmonary +\n 12 * coagulopathy +\n 0 * deficiency_anemias +\n -5 * depression +\n 1 * diabetes_complicated +\n 0 * diabetes_uncomplicated +\n -11 * drug_abuse +\n 11 * fluid_electrolyte +\n -2 * hypertension +\n 0 * hypothyroidism +\n 7 * liver_disease +\n 8 * lymphoma +\n 17 * metastatic_cancer +\n 5 * other_neurological +\n -5 * obesity +\n 4 * paralysis +\n 0 * peptic_ulcer +\n 4 * peripheral_vascular +\n -6 * psychoses +\n 5 * pulmonary_circulation +\n 7 * renal_failure +\n 0 * rheumatoid_arthritis +\n 10 * solid_tumor +\n 0 * valvular_disease +\n 10 * weight_loss\nas elixhauser_SID30\n\nfrom comorbidity_elixhauser_ahrq_v37;\n-- jing add tail\nalter table mimic3.comorbidity_elixhauser_score_ahrq\nowner to postgres;\n"
elixhauser_score_quan <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS comorbidity_elixhauser_score_quan;\ncreate materialized view mimic3.comorbidity_elixhauser_score_quan\ntablespace pg_default\nas\n-- jing add head\n-- This query provides various methods of combining the Elixhauser components into a single score\n-- The methods are called \"vanWalRaven\" and \"SID30\", and \"SID29\"\n\nselect hadm_id\n, -- Below is the van Walraven score\n0 * aids +\n 0 * alcohol_abuse +\n -2 * blood_loss_anemia +\n 7 * congestive_heart_failure +\n -- Cardiac arrhythmias are not included in van Walraven based on Quan 2007\n3 * chronic_pulmonary +\n 3 * coagulopathy +\n -2 * deficiency_anemias +\n -3 * depression +\n 0 * diabetes_complicated +\n 0 * diabetes_uncomplicated +\n -7 * drug_abuse +\n 5 * fluid_electrolyte +\n 0 * hypertension +\n 0 * hypothyroidism +\n 11 * liver_disease +\n 9 * lymphoma +\n 12 * metastatic_cancer +\n 6 * other_neurological +\n -4 * obesity +\n 7 * paralysis +\n 2 * peripheral_vascular +\n 0 * peptic_ulcer +\n 0 * psychoses +\n 4 * pulmonary_circulation +\n 0 * rheumatoid_arthritis +\n 5 * renal_failure +\n 4 * solid_tumor +\n -1 * valvular_disease +\n 6 * weight_loss\nas elixhauser_vanwalraven\n\n\n\n, -- Below is the 29 component SID score\n0 * aids +\n -2 * alcohol_abuse +\n -2 * blood_loss_anemia +\n -- Cardiac arrhythmias are not included in SID-29\n9 * congestive_heart_failure +\n 3 * chronic_pulmonary +\n 9 * coagulopathy +\n 0 * deficiency_anemias +\n -4 * depression +\n 0 * diabetes_complicated +\n -1 * diabetes_uncomplicated +\n -8 * drug_abuse +\n 9 * fluid_electrolyte +\n -1 * hypertension +\n 0 * hypothyroidism +\n 5 * liver_disease +\n 6 * lymphoma +\n 13 * metastatic_cancer +\n 4 * other_neurological +\n -4 * obesity +\n 3 * paralysis +\n 0 * peptic_ulcer +\n 4 * peripheral_vascular +\n -4 * psychoses +\n 5 * pulmonary_circulation +\n 6 * renal_failure +\n 0 * rheumatoid_arthritis +\n 8 * solid_tumor +\n 0 * valvular_disease +\n 8 * weight_loss\nas elixhauser_SID29\n\n\n, -- Below is the 30 component SID score\n0 * aids +\n 0 * alcohol_abuse +\n -3 * blood_loss_anemia +\n 8 * cardiac_arrhythmias +\n 9 * congestive_heart_failure +\n 3 * chronic_pulmonary +\n 12 * coagulopathy +\n 0 * deficiency_anemias +\n -5 * depression +\n 1 * diabetes_complicated +\n 0 * diabetes_uncomplicated +\n -11 * drug_abuse +\n 11 * fluid_electrolyte +\n -2 * hypertension +\n 0 * hypothyroidism +\n 7 * liver_disease +\n 8 * lymphoma +\n 17 * metastatic_cancer +\n 5 * other_neurological +\n -5 * obesity +\n 4 * paralysis +\n 0 * peptic_ulcer +\n 4 * peripheral_vascular +\n -6 * psychoses +\n 5 * pulmonary_circulation +\n 7 * renal_failure +\n 0 * rheumatoid_arthritis +\n 10 * solid_tumor +\n 0 * valvular_disease +\n 10 * weight_loss\nas elixhauser_SID30\n\nfrom comorbidity_elixhauser_quan;\n-- jing add tail\nalter table mimic3.comorbidity_elixhauser_score_quan\nowner to postgres;\n"
# 24 cookbooks ----
age_histogram <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_age_histogram;\ncreate materialized view mimic3.cookbook_age_histogram\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n -- Title: Count the number of hospital admissions in equally sized bins of age\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n -- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- ------------------------------------------------------------------\n \n WITH agetbl AS\n(\n SELECT datetime_diff(ad.admittime, p.dob,'YEAR') AS age\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n)\n, agebin AS\n(\n SELECT age, width_bucket(age, 15, 100, 85) AS bucket\n FROM agetbl\n)\nSELECT bucket+15 as age, count(*)\nFROM agebin\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_age_histogram\nowner to postgres;\n"
basic_patient_info <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_basic_patient_info;\ncreate materialized view mimic3.cookbook_basic_patient_info\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n -- Title: Retrieves basic patient information from the patients table\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n -- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- ------------------------------------------------------------------\n \n \n SELECT subject_id, gender, dob\nFROM patients;\n-- jing add tail\nalter table mimic3.cookbook_basic_patient_info\nowner to postgres;\n"
bun <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_bun;\ncreate materialized view mimic3.cookbook_bun\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Create a distribution of cookbook_bun values for adult hospital admissions\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_bun as\n(\n SELECT width_bucket(valuenum, 0, 280, 280) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid IN (51006)\n)\nSELECT bucket as blood_urea_nitrogen, count(*)\nFROM cookbook_bun\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_bun\nowner to postgres;\n"
gcs <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_gcs;\ncreate materialized view mimic3.cookbook_gcs\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Find the glasgow coma *MOTOR* score for each adult patient\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_gcs as\n(\n SELECT width_bucket(valuenum, 1, 30, 30) AS bucket\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n WHERE itemid IN\n (\n 454 -- \"Motor Response\"\n , 223900 -- \"GCS - Motor Response\"\n )\n)\nSELECT bucket as gcs_Motor_Response, count(*)\nFROM cookbook_gcs\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_gcs\nowner to postgres;\n"
glucose <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_glucose;\ncreate materialized view mimic3.cookbook_glucose\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves a cookbook_glucose histogram of adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, glc as\n(\n SELECT width_bucket(valuenum, 0.5, 1000, 1000) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid IN (50809,50931)\n AND valuenum IS NOT NULL\n)\nSELECT bucket as glucose, count(*)\nFROM glc\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_glucose\nowner to postgres;\n"
hco <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_hco;\ncreate materialized view mimic3.cookbook_hco\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Create a histogram bicarbonate levels for all patients (adults and neonates)\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_hco as\n(\n SELECT width_bucket(valuenum, 0, 231, 231) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid IN (50803, 50804, 50882)\n AND valuenum IS NOT NULL\n)\nSELECT bucket as bicarbonate, count(*)\nFROM cookbook_hco\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_hco\nowner to postgres;\n"
heart_rate <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_heart_rate;\ncreate materialized view mimic3.cookbook_heart_rate\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Create a histogram of heart rates for adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, hr as\n(\n SELECT width_bucket(valuenum, 0, 300, 301) AS bucket\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n WHERE itemid in (211,220045)\n)\nSELECT bucket as heart_rate, count(*)\nFROM hr\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_heart_rate\nowner to postgres;\n"
height <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_height;\ncreate materialized view mimic3.cookbook_height\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Create a histogram of cookbook_heights for all patients\n-- note: some cookbook_height ITEMIDs were not included, which may implicitly exclude\n-- some neonates from this calculation\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH ht AS\n(\n SELECT valuenum, width_bucket(valuenum, 1, 200, 200) AS bucket\n FROM chartevents\n WHERE itemid in (920,226730)\n AND valuenum IS NOT NULL\n AND valuenum > 0\n AND valuenum < 500\n)\nSELECT bucket as height, count(*)\nFROM ht\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_height\nowner to postgres;\n"
icd9agelimited <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icd9agelimited;\ncreate materialized view mimic3.cookbook_icd9agelimited\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Count the number of patients with a specific icd9 code above a certain age\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Reference: tompollard, alistairewj, erinhong for code taken\n-- from cookbook_sodium.sql on the MIMIC III github repository\n-- ------------------------------------------------------------------\n\nWITH agetbl AS \n\t(\n\tSELECT ad.subject_id \n\tFROM admissions ad \n\tINNER JOIN patients p \n\tON ad.subject_id = p.subject_id \n\tWHERE \n\t-- filter to only adults above 30\n\tdatetime_diff(ad.admittime, p.dob,'YEAR') > 30\n\t-- group by subject_id to ensure there is only 1 subject_id per row\n\tGROUP BY ad.subject_id\n\t) \nSELECT COUNT(DISTINCT dia.subject_id) \nAS \"Hypertension Age 30+\" \nfrom diagnoses_icd dia \nINNER JOIN agetbl \nON dia.subject_id = agetbl.subject_id \nWHERE dia.icd9_code \n-- 401% relates to Hypertension\nLIKE '401%';\n-- jing add tail\nalter table mimic3.cookbook_icd9agelimited\nowner to postgres;\n"
icd9count <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icd9count;\ncreate materialized view mimic3.cookbook_icd9count\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Count the number of patients with a specific icd9 code\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Acknowledgement: Credit goes to Kris Kindle\n-- ------------------------------------------------------------------\n\nSELECT COUNT(DISTINCT subject_id) \nAS \"Hypertension\" \nfrom diagnoses_icd \nWHERE icd9_code \n-- 401% will search for all icd9 codes relating to hypertension\nLIKE '401%';\n-- jing add tail\nalter table mimic3.cookbook_icd9count\nowner to postgres;\n"
icd9vagehistogram <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icd9vagehistogram;\ncreate materialized view mimic3.cookbook_icd9vagehistogram\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Count the number of patients with a specific icd9 code and shows the output as a histogram with groups of age\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Acknowledgements: Made with help from Kris Kindle\n-- Reference: tompollard, alistairewj for code taken\n-- from age_hist.sql on the MIMIC III github repository\n-- ------------------------------------------------------------------\n\nWITH diatbl AS\n\t(\n\tSELECT DISTINCT ON (dia.subject_id) dia.subject_id, ad.admittime\n\tfrom diagnoses_icd dia\n\tINNER JOIN admissions ad\n\tON dia.subject_id = ad.subject_id\n\tWHERE dia.icd9_code\n\t-- 401% relates to hypertension\n\tLIKE '401%'\n\t),\nagetbl AS\n\t(\n\tSELECT dt.subject_id, datetime_diff(dt.admittime, p.dob,'YEAR') AS age\n\tFROM diatbl dt\n\tINNER JOIN patients p\n\tON dt.subject_id = p.subject_id\n\t)\nSELECT\n COUNT(*) AS TOTAL,\n COUNT(CASE WHEN age >= 0 AND age < 16 THEN '0 - 15' END) AS \"0-15\",\n COUNT(CASE WHEN age >= 16 AND age < 21 THEN '16 - 20' END) AS \"16-20\",\n COUNT(CASE WHEN age >= 21 AND age < 26 THEN '21 - 25' END) AS \"21-25\",\n COUNT(CASE WHEN age >= 26 AND age < 31 THEN '26 - 30' END) AS \"26-30\",\n COUNT(CASE WHEN age >= 31 AND age < 36 THEN '31 - 35' END) AS \"31-35\",\n COUNT(CASE WHEN age >= 36 AND age < 41 THEN '36 - 40' END) AS \"36-40\",\n COUNT(CASE WHEN age >= 41 AND age < 46 THEN '41 - 45' END) AS \"41-45\",\n COUNT(CASE WHEN age >= 46 AND age < 51 THEN '46 - 50' END) AS \"46-50\",\n COUNT(CASE WHEN age >= 51 AND age < 56 THEN '51 - 55' END) AS \"51-55\",\n COUNT(CASE WHEN age >= 56 AND age < 61 THEN '56 - 60' END) AS \"56-60\",\n COUNT(CASE WHEN age >= 61 AND age < 66 THEN '61 - 65' END) AS \"61-65\",\n COUNT(CASE WHEN age >= 66 AND age < 71 THEN '66 - 70' END) AS \"66-70\",\n COUNT(CASE WHEN age >= 71 AND age < 76 THEN '71 - 75' END) AS \"71-75\",\n COUNT(CASE WHEN age >= 76 AND age < 81 THEN '76 - 80' END) AS \"76-80\",\n COUNT(CASE WHEN age >= 81 AND age < 86 THEN '81 - 85' END) AS \"81-85\",\n COUNT(CASE WHEN age >= 86 AND age < 91 THEN '86 - 90' END) AS \"86-91\",\n COUNT(CASE WHEN age >= 91 THEN 'Over 91' END) AS \">91\"\nFROM agetbl;\n-- jing add tail\nalter table mimic3.cookbook_icd9vagehistogram\nowner to postgres;\n"
icd9vicd9agelimited <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icd9vicd9agelimited;\ncreate materialized view mimic3.cookbook_icd9vicd9agelimited\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Count the number of patients with two specific icd9 codes above a certain age\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Reference: tompollard, alistairewj, erinhong for code taken\n-- from cookbook_sodium.sql on the MIMIC III github repository\n-- ------------------------------------------------------------------\n\nWITH agetbl AS \n\t(\n\tSELECT ad.subject_id \n\tFROM admissions ad \n\tINNER JOIN patients p \n\tON ad.subject_id = p.subject_id \n\tWHERE \n\tdatetime_diff(ad.admittime, p.dob,'YEAR') > 40 \n\tGROUP BY ad.subject_id\n\t) \nSELECT COUNT(DISTINCT dia.subject_id) \nAS \"Obesity vs Hypertension Age 40+\" \nfrom diagnoses_icd dia \nINNER JOIN agetbl \nON dia.subject_id = agetbl.subject_id \nINNER JOIN diagnoses_icd dib \nON dia.subject_id = dib.subject_id \nWHERE dia.icd9_code \n-- 278% relates to obesity\nLIKE '278%' \nAND dib.icd9_code \n-- 401% relates to hypertension\nLIKE '401%';\n-- jing add tail\nalter table mimic3.cookbook_icd9vicd9agelimited\nowner to postgres;\n"
icd9vicd9count <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icd9vicd9count;\ncreate materialized view mimic3.cookbook_icd9vicd9count\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Count the number of patients with two specific icd9 codes\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Acknowledgement: Credit goes to Kris Kindle\n-- ------------------------------------------------------------------\n\nSELECT COUNT(DISTINCT a.subject_id) \nAS \"Obesity and Dyslipidemia\" \nfrom diagnoses_icd a \nINNER JOIN diagnoses_icd b \nON a.subject_id = b.subject_id \nWHERE a.icd9_code\n-- 278% relates to obesity \nLIKE '278%' \nAND b.icd9_code \n-- 272 relates to Dyslipidemia\nLIKE '272%';\n-- jing add tail\nalter table mimic3.cookbook_icd9vicd9count\nowner to postgres;\n"
icustay_days <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_icustay_days;\ncreate materialized view mimic3.cookbook_icustay_days\ntablespace pg_default\nas\n-- jing add head\n\n-- ----------------------------------------------------------\n-- and assign a timestamp to the start and end of each day --\n-- ----------------------------------------------------------\n\n-- ----------\n-- Columns:\n-- ----------\n-- icustay_id\n-- intime\n-- outime\n-- icudayseq_asc: Counting days since arrival in the ICU\n-- 0 = day of arrival in the ICU\n-- 1 = day 1 after arrival\n-- 2 = day 2 after arrival etc\n-- icudayseq_desc: Counting down to the day of discharge from the ICU\n-- 2 = day 2 before discharge etc\n-- 1 = day 1 before discharge\n-- 0 = day of discharge from the ICU\n-- startday: if day of arrival then intime, else midnight at start of day\n-- endday: if day of discharge then outtime, else midnight at end of day\n-- ----------\n\nWITH dayseq AS (\n SELECT icustay_id, intime, outtime,\n GENERATE_SERIES(0,CEIL(los)::INT-1,1) AS icudayseq_asc,\n GENERATE_SERIES(CEIL(los)::INT-1,0,-1) AS icudayseq_desc\n FROM icustays)\nSELECT icustay_id, intime, outtime,\n icudayseq_asc, icudayseq_desc,\n CASE WHEN icudayseq_asc = 0 THEN intime\n ELSE DATETIME_ADD(date_trunc('day', intime), interval '1 DAY' * (icudayseq_asc))\n END AS startday,\n CASE WHEN icudayseq_desc = 0 THEN OUTTIME\n ELSE DATETIME_ADD(date_trunc('day', intime), interval '1 DAY' * (icudayseq_asc+1))\n END AS endday\nFROM dayseq;\n-- jing add tail\nalter table mimic3.cookbook_icustay_days\nowner to postgres;"
min_surviving_bp <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_min_surviving_bp;\ncreate materialized view mimic3.cookbook_min_surviving_bp\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the systolic blood pressure of hospital survivors\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_min_surviving_bp as\n(\n SELECT p.subject_id, ce.icustay_id, min(valuenum) AS min_sbp\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n -- here we filter down to only survivors\n INNER JOIN patients p\n ON ce.subject_id = p.subject_id and p.expire_flag = 0\n WHERE itemid IN (6, 51, 455, 6701, 220179, 220050)\n GROUP BY p.subject_id, ce.icustay_id\n)\n, cookbook_min_surviving_bp_counted as\n(\n SELECT width_bucket(min_sbp, 0, 300, 300) AS bucket\n FROM cookbook_min_surviving_bp\n)\nSELECT bucket as systolic_blood_pressure, count(*)\nFROM cookbook_min_surviving_bp_counted\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_min_surviving_bp\nowner to postgres;\n"
mortality <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_mortality;\ncreate materialized view mimic3.cookbook_mortality\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Calculate in-hospital, 30-day, and 1 year cookbook_mortality (from hospital admission)\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- Inclusion criteria: Adult (>15 year old) patients, *MOST RECENT* hospital admission\n-- ------------------------------------------------------------------\n\nWITH tmp as\n(\n SELECT adm.hadm_id, admittime, dischtime, adm.deathtime, pat.dod\n FROM admissions adm\n INNER JOIN patients pat\n ON adm.subject_id = pat.subject_id\n -- filter out organ donor accounts\n WHERE lower(diagnosis) NOT LIKE '%organ donor%'\n -- at least 15 years old\n AND datetime_diff(admittime, dob,'YEAR') > 15\n -- filter that removes hospital admissions with no corresponding ICU data\n AND HAS_CHARTEVENTS_DATA = 1\n)\nSELECT COUNT(hadm_id) AS NumPat -- total number of patients\n, round( cast(COUNT(deathtime) AS NUMERIC)/COUNT(hadm_id)*100 , 4) AS HospMort -- % hospital cookbook_mortality\n, round( cast(SUM(CASE WHEN dod < DATETIME_ADD(admittime, interval '1 DAY' * (30)) THEN 1 ELSE 0 END) AS NUMERIC)/COUNT(hadm_id)*100.0 , 4) AS HospMort30day -- % 30 day cookbook_mortality\n, round( cast(SUM(CASE WHEN dod < DATETIME_ADD(admittime, interval '1 YEAR' * (1)) THEN 1 ELSE 0 END) AS NUMERIC)/COUNT(hadm_id)*100 , 4) AS HospMort1yr -- % 1 year cookbook_mortality\nFROM tmp;\n-- jing add tail\nalter table mimic3.cookbook_mortality\nowner to postgres;"
number_of_patients <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_number_of_patients;\ncreate materialized view mimic3.cookbook_number_of_patients\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Counts the total number of patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nSELECT count(*)\nFROM patients;\n-- jing add tail\nalter table mimic3.cookbook_number_of_patients\nowner to postgres;\n"
potassium <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_potassium;\ncreate materialized view mimic3.cookbook_potassium\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Creates a histogram of serum cookbook_potassium for adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, k as\n(\n SELECT width_bucket(valuenum, 0, 10, 100) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid IN (50822, 50971)\n)\nSELECT round(cast(bucket as numeric) / 10,2) as potassium_value, count(*)\nFROM k\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_potassium\nowner to postgres;\n"
rr <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_rr;\ncreate materialized view mimic3.cookbook_rr\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the respiration rate of adult patients\n-- only for patients recorded with carevue\n-- MIMIC version: MIMIC-III v1.3\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_rr as\n(\n SELECT valuenum, width_bucket(valuenum, 0, 130, 1400) AS bucket\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n WHERE itemid in (219, 615, 618)\n)\nSELECT round(cast(bucket as numeric) / 10,2) as respiration_rate, count(*)\nFROM cookbook_rr\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_rr\nowner to postgres;\n"
sbp <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_sbp;\ncreate materialized view mimic3.cookbook_sbp\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the systolic blood pressure for adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, sysbp as\n(\n SELECT width_bucket(valuenum, 0, 300, 300) AS bucket\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n WHERE itemid IN\n (\n 6 -- ABP [Systolic]\n , 51 -- Arterial BP [Systolic]\n , 455 -- NBP [Systolic]\n , 6701 -- Arterial BP #2 [Systolic]\n , 220050 -- Arterial Blood Pressure systolic\n , 220179 -- Non Invasive Blood Pressure systolic\n )\n)\nSELECT bucket as systolic_blood_pressure, count(*)\nFROM sysbp\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_sbp\nowner to postgres;\n"
sodium <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_sodium;\ncreate materialized view mimic3.cookbook_sodium\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the blood serum cookbook_sodium levels for adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_sodium as\n(\n SELECT width_bucket(valuenum, 0, 180, 180) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid IN (50824, 50983)\n)\nSELECT bucket as sodium, count(*)\nFROM cookbook_sodium\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_sodium\nowner to postgres;\n"
temp <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_temp;\ncreate materialized view mimic3.cookbook_temp\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the temperature of adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_temp as\n(\n SELECT width_bucket(\n CASE\n WHEN itemid IN (223762, 676, 677) THEN valuenum -- celsius\n WHEN itemid IN (223761, 678, 679) THEN (valuenum - 32) * 5 / 9 --fahrenheit\n END\n , 30, 45, 160) AS bucket\n FROM chartevents ce\n INNER JOIN agetbl\n ON ce.subject_id = agetbl.subject_id\n WHERE itemid IN\n (\n 676 -- temperature C\n , 677 -- temperature C (calc)\n , 678 -- temperature F\n , 679 -- temperature F (calc)\n , 223761 -- temperature Fahrenheit\n , 223762 -- temperature Celsius\n )\n)\nSELECT round((cast(bucket as numeric)/10) + 30,2) as temperature, count(*)\nFROM cookbook_temp\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_temp\nowner to postgres;\n"
uo <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_uo;\ncreate materialized view mimic3.cookbook_uo\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the urine output of adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ie.icustay_id, ie.intime\n FROM icustays ie\n INNER JOIN patients p\n ON ie.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ie.intime, p.dob,'YEAR') > 15\n)\n-- Urine output is measured hourly, but the individual values are not of interest\n-- Usually, you want an overall picture of patient output\n-- This query sums the data over the first 24 hours\n, cookbook_uo_sum as\n(\n select oe.icustay_id, sum(oe.VALUE) as urineoutput\n FROM outputevents oe\n INNER JOIN agetbl\n ON oe.icustay_id = agetbl.icustay_id\n -- and ensure the data occurs during the first day\n and oe.charttime between agetbl.intime and (DATETIME_ADD(agetbl.intime, interval '1 DAY' * (1))) -- first ICU day\n WHERE itemid IN\n (\n -- these are the most frequently occurring urine output observations in CareVue\n 40055, -- \"Urine Out Foley\"\n 43175, -- \"Urine .\"\n 40069, -- \"Urine Out Void\"\n 40094, -- \"Urine Out Condom Cath\"\n 40715, -- \"Urine Out Suprapubic\"\n 40473, -- \"Urine Out IleoConduit\"\n 40085, -- \"Urine Out Incontinent\"\n 40057, -- \"Urine Out Rt Nephrostomy\"\n 40056, -- \"Urine Out Lt Nephrostomy\"\n 40405, -- \"Urine Out Other\"\n 40428, -- \"Urine Out Straight Cath\"\n 40086,-- Urine Out Incontinent\n 40096, -- \"Urine Out Ureteral Stent #1\"\n 40651, -- \"Urine Out Ureteral Stent #2\"\n\n -- these are the most frequently occurring urine output observations in Metavision\n 226559, -- \"Foley\"\n 226560, -- \"Void\"\n 227510, -- \"TF Residual\"\n 226561, -- \"Condom Cath\"\n 226584, -- \"Ileoconduit\"\n 226563, -- \"Suprapubic\"\n 226564, -- \"R Nephrostomy\"\n 226565, -- \"L Nephrostomy\"\n 226567, -- Straight Cath\n 226557, -- \"R Ureteral Stent\"\n 226558 -- \"L Ureteral Stent\"\n )\n group by oe.icustay_id\n)\n, cookbook_uo as\n(\n SELECT width_bucket(urineoutput, 0, 5000, 50) AS bucket\n FROM cookbook_uo_sum\n)\nSELECT bucket*100 as UrineOutput, COUNT(*)\nFROM cookbook_uo\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_uo\nowner to postgres;"
wbc <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS cookbook_wbc;\ncreate materialized view mimic3.cookbook_wbc\ntablespace pg_default\nas\n-- jing add head\n-- --------------------------------------------------------\n-- Title: Retrieves the white blood cell count for adult patients\n-- Notes: this query does not specify a schema. To run it on your local\n-- MIMIC schema, run the following command:\n-- SET SEARCH_PATH TO mimic3;\n-- Where \"mimic3\" is the name of your schema, and may be different.\n-- --------------------------------------------------------\n\nWITH agetbl AS\n(\n SELECT ad.subject_id\n FROM admissions ad\n INNER JOIN patients p\n ON ad.subject_id = p.subject_id\n WHERE\n -- filter to only adults\n datetime_diff(ad.admittime, p.dob,'YEAR') > 15\n -- group by subject_id to ensure there is only 1 subject_id per row\n group by ad.subject_id\n)\n, cookbook_wbc as\n(\n SELECT width_bucket(valuenum, 0, 100, 1001) AS bucket\n FROM labevents le\n INNER JOIN agetbl\n ON le.subject_id = agetbl.subject_id\n WHERE itemid in (51300, 51301)\n AND valuenum IS NOT NULL\n)\nSELECT round((cast(bucket as numeric)/10),2) as white_blood_cell_count, count(*)\nFROM cookbook_wbc\nGROUP BY bucket\nORDER BY bucket;\n-- jing add tail\nalter table mimic3.cookbook_wbc\nowner to postgres;\n"
# 5 demographics----
heightweight <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS demographics_heightweight;\ncreate materialized view mimic3.demographics_heightweight\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Extract height and weight for ICUSTAY_IDs\n-- Description: This query gets the first, minimum, and maximum weight and height\n-- for a single ICUSTAY_ID. It extracts data from the CHARTEVENTS table.\n-- MIMIC version: MIMIC-III v1.4\n-- ------------------------------------------------------------------\n\n-- prep height\nWITH ht_stg AS\n(\n SELECT \n c.subject_id, c.icustay_id, c.charttime,\n -- Ensure that all heights are in centimeters, and fix data as needed\n CASE\n WHEN c.itemid IN (920, 1394, 4187, 3486, 226707)\n THEN\n CASE\n -- rule for neonates\n WHEN c.charttime <= DATETIME_ADD(pt.dob, interval '1 YEAR' * (1))\n AND (c.valuenum * 2.54) < 80\n THEN c.valuenum * 2.54\n -- rule for adults\n WHEN c.charttime > DATETIME_ADD(pt.dob, interval '1 YEAR' * (1))\n AND (c.valuenum * 2.54) > 120\n AND (c.valuenum * 2.54) < 230\n THEN c.valuenum * 2.54\n ELSE NULL END\n ELSE\n CASE\n -- rule for neonates\n WHEN c.charttime <= DATETIME_ADD(pt.dob, interval '1 YEAR' * (1))\n AND c.valuenum < 80\n THEN c.valuenum\n -- rule for adults\n WHEN c.charttime > DATETIME_ADD(pt.dob, interval '1 YEAR' * (1))\n AND c.valuenum > 120\n AND c.valuenum < 230\n THEN c.valuenum\n ELSE NULL END\n END AS height\n FROM chartevents c\n INNER JOIN patients pt\n ON c.subject_id = pt.subject_id\n WHERE c.valuenum IS NOT NULL\n AND c.valuenum != 0\n -- exclude rows marked as error\n AND COALESCE(c.error, 0) = 0\n AND c.itemid IN\n (\n -- CareVue\n 920, 1394, 4187, 3486, -- height inches\n 3485, 4188 -- height cm\n -- Metavision\n , 226707 -- height (measured in inches)\n -- note we intentionally ignore the below ITEMID in metavision\n -- these are duplicate data in a different unit\n -- , 226730 -- height (cm)\n )\n)\nSELECT \n ie.icustay_id,\n ROUND(CAST(wt.weight_first AS NUMERIC), 2) AS weight_first,\n ROUND(CAST(wt.weight_min AS NUMERIC), 2) AS weight_min,\n ROUND(CAST(wt.weight_max AS NUMERIC), 2) AS weight_max,\n ROUND(CAST(ht.height_first AS NUMERIC), 2) AS height_first,\n ROUND(CAST(ht.height_min AS NUMERIC), 2) AS height_min,\n ROUND(CAST(ht.height_max AS NUMERIC), 2) AS height_max\nFROM icustays ie\n
-- get weight from durations_weight_durations table\nLEFT JOIN\n(\n SELECT icustay_id,\n MIN(CASE WHEN rn = 1 THEN weight ELSE NULL END) as weight_first,\n MIN(weight) AS weight_min,\n MAX(weight) AS weight_max\n FROM\n (\n SELECT\n icustay_id,\n weight,\n ROW_NUMBER() OVER (PARTITION BY icustay_id ORDER BY starttime) as rn\n FROM durations_weight_durations\n ) wt_stg\n GROUP BY icustay_id\n) wt\n ON ie.icustay_id = wt.icustay_id\n-- get first/min/max height from above, after filtering bad data\nLEFT JOIN\n(\n SELECT icustay_id,\n MIN(CASE WHEN rn = 1 THEN height ELSE NULL END) as height_first,\n MIN(height) AS height_min,\n MAX(height) AS height_max\n FROM\n (\n SELECT\n icustay_id,\n height,\n ROW_NUMBER() OVER (PARTITION BY icustay_id ORDER BY charttime) as rn\n FROM ht_stg\n ) ht_stg2\n GROUP BY icustay_id\n) ht\n ON ie.icustay_id = ht.icustay_id\nORDER BY icustay_id;\n-- jing add tail\nalter table mimic3.demographics_heightweight\nowner to postgres;"
icustay_detail <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS demographics_icustay_detail;\ncreate materialized view mimic3.demographics_icustay_detail\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Detailed information on ICUSTAY_ID\n-- Description: This query provides a useful set of information regarding patient\n-- ICU stays. The information is combined from the admissions, patients, and\n-- icustays tables. It includes age, length of stay, sequence, and expiry flags.\n-- MIMIC version: MIMIC-III v1.3\n-- ------------------------------------------------------------------\n\n-- This query extracts useful demographic/administrative information for patient ICU stays\n\nSELECT ie.subject_id, ie.hadm_id, ie.icustay_id\n\n-- patient level factors\n, pat.gender, pat.dod\n\n-- hospital level factors\n, adm.admittime, adm.dischtime\n, datetime_diff(adm.dischtime, adm.admittime, 'DAY') as los_hospital\n, datetime_diff(ie.intime, pat.dob, 'YEAR') as admission_age\n, adm.ethnicity\n, case when ethnicity in\n (\n 'WHITE' -- 40996\n , 'WHITE - RUSSIAN' -- 164\n , 'WHITE - OTHER EUROPEAN' -- 81\n , 'WHITE - BRAZILIAN' -- 59\n , 'WHITE - EASTERN EUROPEAN' -- 25\n ) then 'white'\n when ethnicity in\n (\n 'BLACK/AFRICAN AMERICAN' -- 5440\n , 'BLACK/CAPE VERDEAN' -- 200\n , 'BLACK/HAITIAN' -- 101\n , 'BLACK/AFRICAN' -- 44\n , 'CARIBBEAN ISLAND' -- 9\n ) then 'black'\n when ethnicity in\n (\n 'HISPANIC OR LATINO' -- 1696\n , 'HISPANIC/LATINO - PUERTO RICAN' -- 232\n , 'HISPANIC/LATINO - DOMINICAN' -- 78\n , 'HISPANIC/LATINO - GUATEMALAN' -- 40\n , 'HISPANIC/LATINO - CUBAN' -- 24\n , 'HISPANIC/LATINO - SALVADORAN' -- 19\n , 'HISPANIC/LATINO - CENTRAL AMERICAN (OTHER)' -- 13\n , 'HISPANIC/LATINO - MEXICAN'
-- 13\n , 'HISPANIC/LATINO - COLOMBIAN' -- 9\n , 'HISPANIC/LATINO - HONDURAN' -- 4\n ) then 'hispanic'\n when ethnicity in\n (\n 'ASIAN' -- 1509\n , 'ASIAN - CHINESE' -- 277\n , 'ASIAN - ASIAN INDIAN' -- 85\n , 'ASIAN - VIETNAMESE' -- 53\n , 'ASIAN - FILIPINO' -- 25\n , 'ASIAN - CAMBODIAN' -- 17\n , 'ASIAN - OTHER' -- 17\n , 'ASIAN - KOREAN' -- 13\n , 'ASIAN - JAPANESE' -- 7\n , 'ASIAN - THAI' -- 4\n ) then 'asian'\n when ethnicity in\n (\n 'AMERICAN INDIAN/ALASKA NATIVE' -- 51\n , 'AMERICAN INDIAN/ALASKA NATIVE FEDERALLY RECOGNIZED TRIBE' -- 3\n ) then 'native'\n when ethnicity in\n (\n 'UNKNOWN/NOT SPECIFIED' -- 4523\n , 'UNABLE TO OBTAIN' -- 814\n , 'PATIENT DECLINED TO ANSWER' -- 559\n ) then 'unknown'\n else 'other' end as ethnicity_grouped\n -- , 'OTHER' -- 1512\n -- , 'MULTI RACE ETHNICITY' -- 130\n -- , 'PORTUGUESE' -- 61\n -- , 'MIDDLE EASTERN' -- 43\n -- , 'NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER' -- 18\n -- , 'SOUTH AMERICAN' -- 8\n, adm.hospital_expire_flag\n, DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) AS hospstay_seq\n, CASE\n WHEN DENSE_RANK() OVER (PARTITION BY adm.subject_id ORDER BY adm.admittime) = 1 THEN True\n ELSE False END AS first_hosp_stay\n\n-- icu level factors\n, ie.intime, ie.outtime\n, datetime_diff(ie.outtime, ie.intime, 'DAY') as los_icu\n, DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) AS icustay_seq\n\n-- first ICU stay *for the current hospitalization*\n, CASE\n WHEN DENSE_RANK() OVER (PARTITION BY ie.hadm_id ORDER BY ie.intime) = 1 THEN True\n ELSE False END AS first_icu_stay\n\nFROM icustays ie\nINNER JOIN admissions adm\n ON ie.hadm_id = adm.hadm_id\nINNER JOIN patients pat\n ON ie.subject_id = pat.subject_id\nWHERE adm.has_chartevents_data = 1\nORDER BY ie.subject_id, adm.admittime, ie.intime;\n-- jing add tail\nalter table mimic3.demographics_icustay_detail\nowner to postgres;"
icustay_times <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS demographics_icustay_times;\ncreate materialized view mimic3.demographics_icustay_times\ntablespace pg_default\nas\n-- jing add head\n-- involves first creating a lag/lead version of disch/admit time\nwith h as\n(\n select\n subject_id, hadm_id, admittime, dischtime\n , lag (dischtime) over (partition by subject_id order by admittime) as dischtime_lag\n , lead (admittime) over (partition by subject_id order by admittime) as admittime_lead\n FROM admissions\n)\n, adm as\n(\n select\n h.subject_id, h.hadm_id\n -- this rule is:\n -- if there are two hospitalizations within 24 hours, set the start/stop\n -- time as half way between the two admissions\n , case\n when h.dischtime_lag is not null\n and h.dischtime_lag > (DATETIME_SUB(h.admittime, interval '1 HOUR' * (24)))\n then DATETIME_SUB(h.admittime, interval '1 SECOND' * (CAST(datetime_diff(h.admittime, h.dischtime_lag, 'SECOND')/2 AS bigint)))\n else DATETIME_SUB(h.admittime, interval '1 HOUR' * (12))\n end as data_start\n , case\n when h.admittime_lead is not null\n and h.admittime_lead < (DATETIME_ADD(h.dischtime, interval '1 HOUR' * (24)))\n then DATETIME_ADD(h.dischtime, interval '1 SECOND' * (CAST(datetime_diff(h.admittime_lead, h.dischtime, 'SECOND')/2 AS bigint)))\n else (DATETIME_ADD(h.dischtime, interval '1 HOUR' * (12)))\n end as data_end\n from h\n)\n-- get first/last heart rate measurement during hospitalization for each ICUSTAY_ID\n, t1 as\n(\nselect ce.icustay_id\n, min(charttime) as intime_hr\n, max(charttime) as outtime_hr\nFROM chartevents ce\n-- very loose join to admissions to ensure charttime is near patient admission\ninner join adm\n on ce.hadm_id = adm.hadm_id\n and ce.charttime >= adm.data_start\n and ce.charttime < adm.data_end\n-- only look at heart rate\nwhere ce.itemid in (211,220045)\ngroup by ce.icustay_id\n)\n-- add in subject_id/hadm_id\nselect\n ie.subject_id, ie.hadm_id, ie.icustay_id\n , t1.intime_hr\n , t1.outtime_hr\nFROM icustays ie\nleft join t1\n on ie.icustay_id = t1.icustay_id\norder by ie.subject_id, ie.hadm_id, ie.icustay_id;\n-- jing add tail\nalter table mimic3.demographics_icustay_times\nowner to postgres;"
icustay_hours <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS demographics_icustay_hours;\ncreate materialized view mimic3.demographics_icustay_hours\ntablespace pg_default\nas\n-- jing add head\n-- This query generates a row for every hour the patient is in the ICU.\n-- The hours are based on clock-hours (i.e. 02:00, 03:00).\n-- The hour clock starts 24 hours before the first heart rate measurement.\n-- Note that the time of the first heart rate measurement is ceilinged to the hour.\n\n-- this query extracts the cohort and every possible hour they were in the ICU\n-- this table can be to other tables on ICUSTAY_ID and (ENDTIME - 1 hour,ENDTIME]\n\n-- get first/last measurement time\nwith all_hours as\n(\nselect\n it.icustay_id\n\n -- ceiling the intime to the nearest hour by adding 59 minutes then truncating\n -- note thart we truncate by parsing as string, rather than using DATETIME_TRUNC\n -- this is done to enable compatibility with psql\n , PARSE_DATETIME(\n '%Y-%m-%d %H:00:00',\n FORMAT_DATETIME(\n '%Y-%m-%d %H:00:00',\n DATETIME_ADD(it.intime_hr, interval '1 MINUTE' * ('59'))\n )) AS endtime\n\n -- create integers for each charttime in hours from admission\n -- so 0 is admission time, 1 is one hour after admission, etc, up to ICU disch\n -- we allow 24 hours before ICU admission (to grab labs before admit)\n , GENERATE_ARRAY(-24, CEIL(datetime_diff(it.outtime_hr, it.intime_hr, 'HOUR'))::integer) as hrs\n\n from demographics_icustay_times it\n)\nSELECT icustay_id\n, CAST(hr AS bigint) as hr\n, DATETIME_ADD(endtime, interval '1 HOUR' * (CAST(hr AS bigint))) as endtime\nFROM all_hours\nCROSS JOIN UNNEST(array[all_hours.hrs]) AS hr;\n-- jing add tail\nalter table mimic3.demographics_icustay_hours\nowner to postgres;"
note_counts <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS demographics_note_counts;\n\nCREATE EXTENSION IF NOT EXISTS tablefunc;\ncreate materialized view mimic3.demographics_note_counts\n\ntablespace pg_default\nas\n WITH groupnotes AS (\n SELECT\n ct.hadm_id,\n ct.case_management,\n ct.consult,\n ct.discharge_summary,\n ct.ecg,\n ct.echo,\n ct.general,\n ct.nursing,\n ct.nursing_other,\n ct.nutrition,\n ct.pharmacy,\n ct.physician,\n ct.radiology,\n ct.rehab_services,\n ct.respiratory,\n ct.social_work\n FROM crosstab(\n 'select noteevents.hadm_id as hadm_id, noteevents.category as note_type, count(noteevents.text) as notes_count FROM noteevents where noteevents.hadm_id is not null GROUP BY noteevents.hadm_id,noteevents.category order by 1,2' :: TEXT,\n 'select Distinct noteevents.category FROM noteevents order by 1' :: TEXT) ct(hadm_id INTEGER, case_management INTEGER, consult INTEGER, discharge_summary INTEGER, ecg INTEGER, echo INTEGER, general INTEGER, nursing INTEGER, nursing_other INTEGER, nutrition INTEGER, pharmacy INTEGER, physician INTEGER, radiology INTEGER, rehab_services INTEGER, respiratory INTEGER, social_work INTEGER)\n ), totalnotes AS (\n SELECT\n noteevents.hadm_id,\n count(noteevents.text) AS notes_count\n FROM noteevents\n WHERE (noteevents.hadm_id IS NOT NULL)\n GROUP BY noteevents.hadm_id\n ORDER BY noteevents.hadm_id\n )\n SELECT\n admissions.subject_id,\n admissions.hadm_id,\n (admissions.dischtime - admissions.admittime) AS length_of_stay,\n date_part('epoch' :: TEXT, (admissions.dischtime -\n admissions.admittime)) AS length_of_stay_epoch,\n CASE\n WHEN (totalnotes.notes_count IS NULL)\n THEN '0' :: BIGINT\n ELSE totalnotes.notes_count\n END AS total_notes,\n CASE\n WHEN (groupnotes.case_management IS NULL)\n THEN 0\n ELSE groupnotes.case_management\n END AS case_management,\n CASE\n WHEN (groupnotes.consult IS NULL)\n THEN 0\n ELSE groupnotes.consult\n END AS consult,\n CASE\n WHEN (groupnotes.discharge_summary IS NULL)\n THEN 0\n ELSE groupnotes.discharge_summary\n END AS discharge_summary,\n CASE\n WHEN (groupnotes.ecg IS NULL)\n THEN 0\n ELSE groupnotes.ecg\n END AS ecg,\n CASE\n WHEN (groupnotes.echo IS NULL)\n THEN 0\n ELSE groupnotes.echo\n END AS echo,\n CASE\n WHEN (groupnotes.general IS NULL)\n THEN 0\n ELSE groupnotes.general\n END AS general,\n CASE\n WHEN (groupnotes.nursing IS NULL)\n THEN 0\n ELSE groupnotes.nursing\n END AS nursing,\n CASE\n WHEN (groupnotes.nursing_other IS NULL)\n THEN 0\n ELSE groupnotes.nursing_other\n END AS nursing_other,\n CASE\n WHEN (groupnotes.nutrition IS NULL)\n THEN 0\n ELSE groupnotes.nutrition\n END AS nutrition,\n
CASE\n WHEN (groupnotes.pharmacy IS NULL )\n THEN 0\n ELSE groupnotes.pharmacy\n END AS pharmacy,\n CASE\n WHEN (groupnotes.physician IS NULL)\n THEN 0\n ELSE groupnotes.physician\n END AS physician,\n CASE\n WHEN (groupnotes.radiology IS NULL)\n THEN 0\n ELSE groupnotes.radiology\n END AS radiology,\n CASE\n WHEN (groupnotes.rehab_services IS NULL)\n THEN 0\n ELSE groupnotes.rehab_services\n END AS rehab_services,\n CASE\n WHEN (groupnotes.respiratory IS NULL)\n THEN 0\n ELSE groupnotes.respiratory\n END AS respiratory,\n CASE\n WHEN (groupnotes.social_work IS NULL)\n THEN 0\n ELSE groupnotes.social_work\n END AS social_work\n FROM admissions\n LEFT JOIN groupnotes\n ON admissions.hadm_id = groupnotes.hadm_id\n LEFT JOIN totalnotes \n ON admissions.hadm_id = totalnotes.hadm_id\n ORDER BY admissions.subject_id, admissions.hadm_id;\n
-- jing add tail\nalter table mimic3.demographics_note_counts\nowner to postgres;"
# firstday'
blood_gas_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_blood_gas;\ncreate materialized view mimic3.firstday_blood_gas\ntablespace pg_default\nas\n-- jing add head\n-- The aim of this query is to pivot entries related to blood gases and\n-- chemistry values which were found in LABEVENTS\n\n-- things to check:\n-- when a mixed venous/arterial blood sample are taken at the same time, is the store time different?\n\nwith pvt as\n( -- begin query that extracts the data\n select ie.subject_id, ie.hadm_id, ie.icustay_id\n -- here we assign labels to ITEMIDs\n -- this also fuses together multiple ITEMIDs containing the same data\n , case\n when itemid = 50800 then 'SPECIMEN'\n when itemid = 50801 then 'AADO2'\n when itemid = 50802 then 'BASEEXCESS'\n when itemid = 50803 then 'BICARBONATE'\n when itemid = 50804 then 'TOTALCO2'\n when itemid = 50805 then 'CARBOXYHEMOGLOBIN'\n when itemid = 50806 then 'CHLORIDE'\n when itemid = 50808 then 'CALCIUM'\n when itemid = 50809 then 'GLUCOSE'\n when itemid = 50810 then 'HEMATOCRIT'\n when itemid = 50811 then 'HEMOGLOBIN'\n when itemid = 50812 then 'INTUBATED'\n when itemid = 50813 then 'LACTATE'\n when itemid = 50814 then 'METHEMOGLOBIN'\n when itemid = 50815 then 'O2FLOW'\n when itemid = 50816 then 'FIO2'\n when itemid = 50817 then 'SO2' -- OXYGENSATURATION\n when itemid = 50818 then 'PCO2'\n when itemid = 50819 then 'PEEP'\n when itemid = 50820 then 'PH'\n when itemid = 50821 then 'PO2'\n when itemid = 50822 then 'POTASSIUM'\n when itemid = 50823 then 'REQUIREDO2'\n when itemid = 50824 then 'SODIUM'\n when itemid = 50825 then 'TEMPERATURE'\n when itemid = 50826 then 'TIDALVOLUME'\n when itemid = 50827 then 'VENTILATIONRATE'\n when itemid = 50828 then 'VENTILATOR'\n else null\n end as label\n , charttime\n , value\n -- add in some sanity checks on the values\n ,
case\n when valuenum <= 0 and itemid != 50802 then null -- allow negative baseexcess\n when itemid = 50810 and valuenum > 100 then null -- hematocrit\n -- ensure FiO2 is a valid number between 21-100\n -- mistakes are rare (<100 obs out of ~100,000)\n -- there are 862 obs of valuenum == 20 - some people round down!\n -- rather than risk imputing garbage data for FiO2, we simply NULL invalid values\n when itemid = 50816 and valuenum < 20 then null\n when itemid = 50816 and valuenum > 100 then null\n when itemid = 50817 and valuenum > 100 then null -- O2 sat\n when itemid = 50815 and valuenum > 70 then null -- O2 flow\n when itemid = 50821 and valuenum > 800 then null -- PO2\n -- conservative upper limit\n else valuenum\n end as valuenum\n\n FROM icustays ie\n left join labevents le\n on le.subject_id = ie.subject_id and le.hadm_id = ie.hadm_id\n and le.charttime between (DATETIME_SUB(ie.intime, INTERVAL '6' HOUR)) and (DATETIME_ADD(ie.intime, INTERVAL '1' DAY))\n and le.ITEMID in\n -- blood gases\n (\n 50800, 50801, 50802, 50803, 50804, 50805, 50806, 50807, 50808, 50809\n , 50810, 50811, 50812, 50813, 50814, 50815, 50816, 50817, 50818, 50819\n , 50820, 50821, 50822, 50823, 50824, 50825, 50826, 50827, 50828\n , 51545\n )\n)\nselect pvt.SUBJECT_ID, pvt.HADM_ID, pvt.ICUSTAY_ID, pvt.CHARTTIME\n, max(case when label = 'SPECIMEN' then value else null end) as specimen\n, max(case when label = 'AADO2' then valuenum else null end) as aado2\n, max(case when label = 'BASEEXCESS' then valuenum else null end) as baseexcess\n, max(case when label = 'BICARBONATE' then valuenum else null end) as bicarbonate\n, max(case when label = 'TOTALCO2' then valuenum else null end) as totalco2\n, max(case when label = 'CARBOXYHEMOGLOBIN' then valuenum else null end) as carboxyhemoglobin\n, max(case when label = 'CHLORIDE' then valuenum else null end) as chloride\n, max(case when label = 'CALCIUM' then valuenum else null end) as calcium\n, max(case when label = 'GLUCOSE' then valuenum else null end) as glucose\n, max(case when label = 'HEMATOCRIT' then valuenum else null end) as hematocrit\n, max(case when label = 'HEMOGLOBIN' then valuenum else null end) as hemoglobin\n, max(case when label = 'INTUBATED' then valuenum else null end) as intubated\n, max(case when label = 'LACTATE' then valuenum else null end) as lactate\n, max(case when label = 'METHEMOGLOBIN' then valuenum else null end) as methemoglobin\n, max(case when label = 'O2FLOW' then valuenum else null end) as o2flow\n, max(case when label = 'FIO2' then valuenum else null end) as fio2\n, max(case when label = 'SO2' then valuenum else null end) as so2 -- OXYGENSATURATION\n, max(case when label = 'PCO2' then valuenum else null end) as pco2\n, max(case when label = 'PEEP' then valuenum else null end) as peep\n, max(case when label = 'PH' then valuenum else null end) as ph\n, max(case when label = 'PO2' then valuenum else null end) as po2\n, max(case when label = 'POTASSIUM' then valuenum else null end) as potassium\n, max(case when label = 'REQUIREDO2' then valuenum else null end) as requiredo2\n, max(case when label = 'SODIUM' then valuenum else null end) as sodium\n, max(case when label = 'TEMPERATURE' then valuenum else null end) as temperature\n, max(case when label = 'TIDALVOLUME' then valuenum else null end) as tidalvolume\n, max(case when label = 'VENTILATIONRATE' then valuenum else null end) as ventilationrate\n, max(case when label = 'VENTILATOR' then valuenum else null end) as ventilator\nfrom pvt\ngroup by pvt.subject_id, pvt.hadm_id, pvt.icustay_id, pvt.CHARTTIME\norder by pvt.subject_id, pvt.hadm_id, pvt.icustay_id, pvt.CHARTTIME;\n-- jing add tail\nalter table mimic3.firstday_blood_gas\nowner to postgres;\n"
blood_gas_first_day_arterial <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_blood_gas_arterial;\ncreate materialized view mimic3.firstday_blood_gas_arterial\ntablespace pg_default\nas\n-- jing add head\n\nwith stg_spo2 as\n(\n select subject_id, hadm_id, icustay_id, charttime\n -- max here is just used to group SpO2 by charttime\n , max(case when valuenum <= 0 or valuenum > 100 then null else valuenum end) as SpO2\n FROM chartevents\n -- o2 sat\n where ITEMID in\n (\n 646 -- SpO2\n , 220277 -- O2 saturation pulseoxymetry\n )\n group by subject_id, hadm_id, icustay_id, charttime\n)\n, stg_fio2 as\n(\n select subject_id, hadm_id, icustay_id, charttime\n -- pre-process the FiO2s to ensure they are between 21-100%\n , max(\n case\n when itemid = 223835\n then case\n when valuenum > 0 and valuenum <= 1\n then valuenum * 100\n -- improperly input data - looks like O2 flow in litres\n when valuenum > 1 and valuenum < 21\n then null\n when valuenum >= 21 and valuenum <= 100\n then valuenum\n else null end -- unphysiological\n when itemid in (3420, 3422)\n -- all these values are well formatted\n then valuenum\n when itemid = 190 and valuenum > 0.20 and valuenum < 1\n -- well formatted but not in %\n then valuenum * 100\n else null end\n ) as fio2_chartevents\n FROM chartevents\n where ITEMID in\n (\n 3420 -- FiO2\n , 190 -- FiO2 set\n , 223835 -- Inspired O2 Fraction (FiO2)\n , 3422 -- FiO2 [measured]\n )\n -- exclude rows marked as error\n AND (error IS NULL OR error = 0)\n group by subject_id, hadm_id, icustay_id, charttime\n)\n, stg2 as\n(\nselect bg.*\n , ROW_NUMBER() OVER (partition by bg.icustay_id, bg.charttime order by s1.charttime DESC) as lastRowSpO2\n , s1.spo2\nfrom firstday_blood_gas bg\nleft join stg_spo2 s1\n -- same patient\n on bg.icustay_id = s1.icustay_id\n -- spo2 occurred at most 2 hours before this blood gas\n and s1.charttime >= DATETIME_SUB(bg.charttime, INTERVAL '2' HOUR)\n and s1.charttime <= bg.charttime\nwhere bg.po2 is not null\n)\n, stg3 as\n(\nselect bg.*\n , ROW_NUMBER() OVER (partition by bg.icustay_id, bg.charttime order by s2.charttime DESC) as lastRowFiO2\n , s2.fio2_chartevents\n\n -- create our specimen prediction\n , 1/(1+exp(-(-0.02544\n + 0.04598 * po2\n + coalesce(-0.15356 * spo2 , -0.15356 * 97.49420 + 0.13429)\n + coalesce( 0.00621 * fio2_chartevents , 0.00621 * 51.49550 + -0.24958)\n + coalesce( 0.10559 * hemoglobin , 0.10559 * 10.32307 + 0.05954)\n + coalesce( 0.13251 * so2 , 0.13251 * 93.66539 + -0.23172)\n + coalesce(-0.01511 * pco2 , -0.01511 * 42.08866 + -0.01630)\n + coalesce( 0.01480 * fio2 , 0.01480 * 63.97836 + -0.31142)\n + coalesce(-0.00200 * aado2 , -0.00200 * 442.21186 + -0.01328)\n + coalesce(-0.03220 * bicarbonate , -0.03220 * 22.96894 + -0.06535)\n + coalesce( 0.05384 * totalco2 , 0.05384 * 24.72632 + -0.01405)\n + coalesce( 0.08202 * lactate , 0.08202 * 3.06436 + 0.06038)\n + coalesce( 0.10956 * ph , 0.10956 * 7.36233 + -0.00617)\n + coalesce( 0.00848 * o2flow , 0.00848 * 7.59362 + -0.35803)\n ))) as SPECIMEN_PROB\nfrom stg2 bg\nleft join stg_fio2 s2\n -- same patient\n on bg.icustay_id = s2.icustay_id\n -- fio2 occurred at most 4 hours before this blood gas\n and s2.charttime between DATETIME_SUB(bg.charttime, INTERVAL '4' HOUR) and bg.charttime\nwhere bg.lastRowSpO2 = 1 -- only the row with the most recent SpO2 (if no SpO2 found lastRowSpO2 = 1)\n)\n\nselect subject_id, hadm_id,\nicustay_id, charttime\n, specimen -- raw data indicating sample type, only present 80% of the time\n\n-- prediction of specimen for missing data\n,
case\n when SPECIMEN is not null then SPECIMEN\n when SPECIMEN_PROB > 0.75 then 'ART'\n else null end as SPECIMEN_PRED\n, specimen_prob\n\n-- oxygen related parameters\n, so2, spo2 -- note spo2 is FROM chartevents\n, po2, pco2\n, fio2_chartevents, fio2\n, aado2\n-- also calculate AADO2\n, case\n when PO2 is not null\n and pco2 is not null\n and coalesce(fio2, fio2_chartevents) is not null\n -- multiple by 100 because FiO2 is in a % but should be a fraction\n then (coalesce(fio2, fio2_chartevents)/100) * (760 - 47) - (pco2/0.8) - po2\n else null\n end as AADO2_calc\n, case\n when PO2 is not null and coalesce(fio2, fio2_chartevents) is not null\n -- multiply by 100 because FiO2 is in a % but should be a fraction\n then 100*PO2/(coalesce(fio2, fio2_chartevents))\n else null\n end as PaO2FiO2\n-- acid-base parameters\n, ph, baseexcess\n, bicarbonate, totalco2\n\n-- blood count parameters\n, hematocrit\n, hemoglobin\n, carboxyhemoglobin\n, methemoglobin\n\n-- chemistry\n, chloride, calcium\n, temperature\n, potassium, sodium\n, lactate\n, glucose\n\n-- ventilation stuff that's sometimes input\n, intubated, tidalvolume, ventilationrate, ventilator\n, peep, o2flow\n, requiredo2\n\nfrom stg3\nwhere lastRowFiO2 = 1 -- only the most recent FiO2\n-- restrict it to *only* arterial samples\nand (specimen = 'ART' or specimen_prob > 0.75)\norder by icustay_id, charttime;\n-- jing add tail\nalter table mimic3.firstday_blood_gas_arterial\nowner to postgres;\n"
gcs_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_gcs;\ncreate materialized view mimic3.firstday_gcs\ntablespace pg_default\nas\n-- jing add head\n-- ITEMIDs used:\n\n-- CAREVUE\n-- 723 as gcsVerbal\n-- 454 as gcsMotor\n-- 184 as gcsEyes\n\n-- METAVISION\n-- 223900 gcs - Verbal Response\n-- 223901 gcs - Motor Response\n-- 220739 gcs - Eye Opening\n\n-- The code combines the ITEMIDs into the carevue itemids, then pivots those\n-- So 223900 is changed to 723, then the ITEMID 723 is pivoted to form gcsVerbal\n\n-- Note:\n-- The gcs for sedated patients is defaulted to 15 in this code.\n-- This is in line with how the data is meant to be collected.\n-- e.g., from the severityscores_saps II publication:\n-- For sedated patients, the Glasgow Coma Score before sedation was used.\n-- This was ascertained either from interviewing the physician who ordered the sedation,\n-- or by reviewing the patient's medical record.\n\nwith base as\n(\n SELECT pvt.ICUSTAY_ID\n , pvt.charttime\n\n -- Easier names - note we coalesced Metavision and CareVue IDs below\n , max(case when pvt.itemid = 454 then pvt.valuenum else null end) as gcsMotor\n , max(case when pvt.itemid = 723 then pvt.valuenum else null end) as gcsVerbal\n , max(case when pvt.itemid = 184 then pvt.valuenum else null end) as gcsEyes\n\n -- If verbal was set to 0 in the below select, then this is an intubated patient\n , case\n when max(case when pvt.itemid = 723 then pvt.valuenum else null end) = 0\n then 1\n else 0\n end as EndoTrachFlag\n\n , ROW_NUMBER ()\n OVER (PARTITION BY pvt.ICUSTAY_ID ORDER BY pvt.charttime ASC) as rn\n\n FROM (\n select l.ICUSTAY_ID\n -- merge the ITEMIDs so that the pivot applies to both metavision/carevue data\n , case\n when l.ITEMID in (723,223900) then 723\n when l.ITEMID in (454,223901) then 454\n when l.ITEMID in (184,220739) then 184\n else l.ITEMID end\n as ITEMID\n\n -- convert the data into a number, reserving a value of 0 for ET/Trach\n ,
case\n -- endotrach/vent is assigned a value of 0, later parsed specially\n when l.ITEMID = 723 and l.VALUE = '1.0 ET/Trach' then 0 -- carevue\n when l.ITEMID = 223900 and l.VALUE = 'No Response-ETT' then 0 -- metavision\n\n else VALUENUM\n end\n as VALUENUM\n , l.CHARTTIME\n FROM chartevents l\n\n -- get intime for charttime subselection\n inner join icustays b\n on l.icustay_id = b.icustay_id\n\n -- Isolate the desired gcs variables\n where l.ITEMID in\n (\n -- 198 -- gcs\n -- gcs components, CareVue\n 184, 454, 723\n -- gcs components, Metavision\n , 223900, 223901, 220739\n )\n -- Only get data for the first 24 hours\n and l.charttime between b.intime and DATETIME_ADD(b.intime, INTERVAL '1' DAY)\n -- exclude rows marked as error\n AND (l.error IS NULL OR l.error = 0)\n ) pvt\n group by pvt.ICUSTAY_ID, pvt.charttime\n)\n, gcs as (\n select b.*\n , b2.GCSVerbal as gcsVerbalPrev\n , b2.GCSMotor as gcsMotorPrev\n , b2.GCSEyes as gcsEyesPrev\n -- Calculate gcs, factoring in special case when they are intubated and prev vals\n -- note that the coalesce are used to implement the following if:\n -- if current value exists, use it\n -- if previous value exists, use it\n -- otherwise, default to normal\n , case\n -- replace gcs during sedation with 15\n when b.GCSVerbal = 0\n then 15\n when b.GCSVerbal is null and b2.GCSVerbal = 0\n then 15\n -- if previously they were intub, but they aren't now, do not use previous gcs values\n when b2.GCSVerbal = 0\n then\n coalesce(b.GCSMotor,6)\n + coalesce(b.GCSVerbal,5)\n + coalesce(b.GCSEyes,4)\n -- otherwise, add up score normally, imputing previous value if none available at current time\n else\n coalesce(b.GCSMotor,coalesce(b2.GCSMotor,6))\n + coalesce(b.GCSVerbal,coalesce(b2.GCSVerbal,5))\n + coalesce(b.GCSEyes,coalesce(b2.GCSEyes,4))\n end as gcs\n\n from base b\n -- join to itself within 6 hours to get previous value\n left join base b2\n on b.ICUSTAY_ID = b2.ICUSTAY_ID and b.rn = b2.rn+1 and b2.charttime > DATETIME_SUB(b.charttime, INTERVAL '6' HOUR)\n)\n, gcs_final as (\n select gcs.*\n -- This sorts the data by gcs, so rn=1 is the the lowest gcs values to keep\n , ROW_NUMBER ()\n OVER (PARTITION BY gcs.ICUSTAY_ID\n ORDER BY gcs.GCS\n ) as IsMinGCS\n from gcs\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n-- The minimum gcs is determined by the above row partition, we only join if IsMinGCS=1\n, gcs as mingcs\n, coalesce(GCSMotor,GCSMotorPrev) as gcsmotor\n, coalesce(GCSVerbal,GCSVerbalPrev) as gcsverbal\n, coalesce(GCSEyes,GCSEyesPrev) as gcseyes\n, EndoTrachFlag as endotrachflag\n\n-- subselect down to the cohort of eligible patients\nFROM icustays ie\nleft join gcs_final gs\n on ie.icustay_id = gs.icustay_id and gs.IsMinGCS = 1\nORDER BY ie.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_gcs\nowner to postgres;\n"
height_first_day <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_height;\ncreate materialized view mimic3.firstday_height\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts heights for adult ICU patients.\n-- It uses all information from the patient's first ICU day.\n-- This is done for consistency with other queries - it's not necessarily needed.\n-- height is unlikely to change throughout a patient's stay.\n\n-- ** Requires the echodata view, generated by concepts/echo-data.sql\n\n-- staging table to ensure all heights are in centimeters\nwith ce0 as\n(\n SELECT\n c.icustay_id\n , case\n -- convert inches to centimetres\n when itemid in (920, 1394, 4187, 3486)\n then valuenum * 2.54\n else valuenum\n end as height\n FROM chartevents c\n inner join icustays ie\n on c.icustay_id = ie.icustay_id\n and c.charttime <= DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and c.charttime > DATETIME_SUB(ie.intime, INTERVAL '1' DAY) -- some fuzziness for admit time\n WHERE c.valuenum IS NOT NULL\n AND c.itemid in (226730,920, 1394, 4187, 3486,3485,4188) -- height\n AND c.valuenum != 0\n -- exclude rows marked as error\n AND (c.error IS NULL OR c.error = 0)\n)\n, ce as\n(\n SELECT\n icustay_id\n -- extract the median height from the chart to add robustness against outliers\n , AVG(height) as height_chart\n from ce0\n where height > 100\n group by icustay_id\n)\n-- requires the echo-data.sql query to run\n-- this adds heights from the free-text echo notes\n, echo as\n(\n select\n ec.subject_id\n -- all echo heights are in inches\n , 2.54*AVG(height) as height_Echo\n from echo_data ec\n inner join icustays ie\n on ec.subject_id = ie.subject_id\n and ec.charttime < DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where height is not null\n and height*2.54 > 100\n group by ec.subject_id\n)\nselect\n ie.icustay_id\n , coalesce(ce.Height_chart, ec.Height_Echo) as height\n\n -- components\n , ce.height_chart\n , ec.height_echo\nFROM icustays ie\n\n-- filter to only adults\ninner join patients pat\n on ie.subject_id = pat.subject_id\n and ie.intime > DATETIME_ADD(pat.dob, INTERVAL '1' YEAR)\n\nleft join ce\n on ie.icustay_id = ce.icustay_id\n\nleft join echo ec\n on ie.subject_id = ec.subject_id;\n-- jing add tail\nalter table mimic3.firstday_height\nowner to postgres;\n"
labs_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_labs;\ncreate materialized view mimic3.firstday_labs\ntablespace pg_default\nas\n-- jing add head\n-- This query pivots lab values taken in the first 24 hours of a patient's stay\n\n-- Have already confirmed that the unit of measurement is always the same: null or the correct unit\n\nSELECT\n pvt.subject_id, pvt.hadm_id, pvt.icustay_id\n\n , min(CASE WHEN label = 'ANION GAP' THEN valuenum ELSE NULL END) AS aniongap_min\n , max(CASE WHEN label = 'ANION GAP' THEN valuenum ELSE NULL END) AS aniongap_max\n , min(CASE WHEN label = 'ALBUMIN' THEN valuenum ELSE NULL END) AS albumin_min\n , max(CASE WHEN label = 'ALBUMIN' THEN valuenum ELSE NULL END) AS albumin_max\n , min(CASE WHEN label = 'BANDS' THEN valuenum ELSE NULL END) AS bands_min\n , max(CASE WHEN label = 'BANDS' THEN valuenum ELSE NULL END) AS bands_max\n , min(CASE WHEN label = 'BICARBONATE' THEN valuenum ELSE NULL END) AS bicarbonate_min\n , max(CASE WHEN label = 'BICARBONATE' THEN valuenum ELSE NULL END) AS bicarbonate_max\n , min(CASE WHEN label = 'BILIRUBIN' THEN valuenum ELSE NULL END) AS bilirubin_min\n , max(CASE WHEN label = 'BILIRUBIN' THEN valuenum ELSE NULL END) AS bilirubin_max\n , min(CASE WHEN label = 'CREATININE' THEN valuenum ELSE NULL END) AS creatinine_min\n , max(CASE WHEN label = 'CREATININE' THEN valuenum ELSE NULL END) AS creatinine_max\n , min(CASE WHEN label = 'CHLORIDE' THEN valuenum ELSE NULL END) AS chloride_min\n , max(CASE WHEN label = 'CHLORIDE' THEN valuenum ELSE NULL END) AS chloride_max\n , min(CASE WHEN label = 'GLUCOSE' THEN valuenum ELSE NULL END) AS glucose_min\n , max(CASE WHEN label = 'GLUCOSE' THEN valuenum ELSE NULL END) AS glucose_max\n , min(CASE WHEN label = 'HEMATOCRIT' THEN valuenum ELSE NULL END) AS hematocrit_min\n , max(CASE WHEN label = 'HEMATOCRIT' THEN valuenum ELSE NULL END) AS hematocrit_max\n , min(CASE WHEN label = 'HEMOGLOBIN' THEN valuenum ELSE NULL END) AS hemoglobin_min\n , max(CASE WHEN label = 'HEMOGLOBIN' THEN valuenum ELSE NULL END) AS hemoglobin_max\n , min(CASE WHEN label = 'LACTATE' THEN valuenum ELSE NULL END) AS lactate_min\n , max(CASE WHEN label = 'LACTATE' THEN valuenum ELSE NULL END) AS lactate_max\n , min(CASE WHEN label = 'PLATELET' THEN valuenum ELSE NULL END) AS platelet_min\n , max(CASE WHEN label = 'PLATELET' THEN valuenum ELSE NULL END) AS platelet_max\n , min(CASE WHEN label = 'POTASSIUM' THEN valuenum ELSE NULL END) AS potassium_min\n , max(CASE WHEN label = 'POTASSIUM' THEN valuenum ELSE NULL END) AS potassium_max\n , min(CASE WHEN label = 'PTT' THEN valuenum ELSE NULL END) AS ptt_min\n , max(CASE WHEN label = 'PTT' THEN valuenum ELSE NULL END) AS ptt_max\n , min(CASE WHEN label = 'INR' THEN valuenum ELSE NULL END) AS inr_min\n , max(CASE WHEN label = 'INR' THEN valuenum ELSE NULL END) AS inr_max\n , min(CASE WHEN label = 'PT' THEN valuenum ELSE NULL END) AS pt_min\n , max(CASE WHEN label = 'PT' THEN valuenum ELSE NULL END) AS pt_max\n , min(CASE WHEN label = 'SODIUM' THEN valuenum ELSE NULL END) AS sodium_min\n , max(CASE WHEN label = 'SODIUM' THEN valuenum ELSE NULL END) AS sodium_max\n , min(CASE WHEN label = 'BUN' THEN valuenum ELSE NULL END) AS bun_min\n , max(CASE WHEN label = 'BUN' THEN valuenum ELSE NULL END) AS bun_max\n , min(CASE WHEN label = 'WBC' THEN valuenum ELSE NULL END) AS wbc_min\n , max(CASE WHEN label = 'WBC' THEN valuenum ELSE NULL END) AS wbc_max\n\n\nFROM\n( -- begin query that extracts the data\n SELECT ie.subject_id, ie.hadm_id, ie.icustay_id\n -- here we assign labels to ITEMIDs\n -- this also fuses together multiple ITEMIDs containing the same data\n ,
CASE\n WHEN itemid = 50868 THEN 'ANION GAP'\n WHEN itemid = 50862 THEN 'ALBUMIN'\n WHEN itemid = 51144 THEN 'BANDS'\n WHEN itemid = 50882 THEN 'BICARBONATE'\n WHEN itemid = 50885 THEN 'BILIRUBIN'\n WHEN itemid = 50912 THEN 'CREATININE'\n WHEN itemid = 50806 THEN 'CHLORIDE'\n WHEN itemid = 50902 THEN 'CHLORIDE'\n WHEN itemid = 50809 THEN 'GLUCOSE'\n WHEN itemid = 50931 THEN 'GLUCOSE'\n WHEN itemid = 50810 THEN 'HEMATOCRIT'\n WHEN itemid = 51221 THEN 'HEMATOCRIT'\n WHEN itemid = 50811 THEN 'HEMOGLOBIN'\n WHEN itemid = 51222 THEN 'HEMOGLOBIN'\n WHEN itemid = 50813 THEN 'LACTATE'\n WHEN itemid = 51265 THEN 'PLATELET'\n WHEN itemid = 50822 THEN 'POTASSIUM'\n WHEN itemid = 50971 THEN 'POTASSIUM'\n WHEN itemid = 51275 THEN 'PTT'\n WHEN itemid = 51237 THEN 'INR'\n WHEN itemid = 51274 THEN 'PT'\n WHEN itemid = 50824 THEN 'SODIUM'\n WHEN itemid = 50983 THEN 'SODIUM'\n WHEN itemid = 51006 THEN 'BUN'\n WHEN itemid = 51300 THEN 'WBC'\n WHEN itemid = 51301 THEN 'WBC'\n ELSE null\n END as label\n , -- add in some sanity checks on the values\n -- the where clause below requires all valuenum to be > 0, so these are only upper limit checks\n
CASE\n WHEN itemid = 50862 and valuenum > 10 THEN null -- g/dL 'ALBUMIN'\n WHEN itemid = 50868 and valuenum > 10000 THEN null -- mEq/L 'ANION GAP'\n WHEN itemid = 51144 and valuenum < 0 THEN null -- immature band forms, %\n WHEN itemid = 51144 and valuenum > 100 THEN null -- immature band forms, %\n WHEN itemid = 50882 and valuenum > 10000 THEN null -- mEq/L 'BICARBONATE'\n WHEN itemid = 50885 and valuenum > 150 THEN null -- mg/dL 'BILIRUBIN'\n WHEN itemid = 50806 and valuenum > 10000 THEN null -- mEq/L 'CHLORIDE'\n WHEN itemid = 50902 and valuenum > 10000 THEN null -- mEq/L 'CHLORIDE'\n WHEN itemid = 50912 and valuenum > 150 THEN null -- mg/dL 'CREATININE'\n WHEN itemid = 50809 and valuenum > 10000 THEN null -- mg/dL 'GLUCOSE'\n WHEN itemid = 50931 and valuenum > 10000 THEN null -- mg/dL 'GLUCOSE'\n WHEN itemid = 50810 and valuenum > 100 THEN null -- % 'HEMATOCRIT'\n WHEN itemid = 51221 and valuenum > 100 THEN null -- % 'HEMATOCRIT'\n WHEN itemid = 50811 and valuenum > 50 THEN null -- g/dL 'HEMOGLOBIN'\n WHEN itemid = 51222 and valuenum > 50 THEN null -- g/dL 'HEMOGLOBIN'\n WHEN itemid = 50813 and valuenum > 50 THEN null -- mmol/L 'LACTATE'\n WHEN itemid = 51265 and valuenum > 10000 THEN null -- K/uL 'PLATELET'\n WHEN itemid = 50822 and valuenum > 30 THEN null -- mEq/L 'POTASSIUM'\n WHEN itemid = 50971 and valuenum > 30 THEN null -- mEq/L 'POTASSIUM'\n WHEN itemid = 51275 and valuenum > 150 THEN null -- sec 'PTT'\n WHEN itemid = 51237 and valuenum > 50 THEN null -- 'INR'\n WHEN itemid = 51274 and valuenum > 150 THEN null -- sec 'PT'\n WHEN itemid = 50824 and valuenum > 200 THEN null -- mEq/L == mmol/L 'SODIUM'\n WHEN itemid = 50983 and valuenum > 200 THEN null -- mEq/L == mmol/L 'SODIUM'\n WHEN itemid = 51006 and valuenum > 300 THEN null -- 'BUN'\n WHEN itemid = 51300 and valuenum > 1000 THEN null -- 'WBC'\n WHEN itemid = 51301 and valuenum > 1000 THEN null -- 'WBC'\n ELSE le.valuenum\n END as valuenum\n\n FROM icustays ie\n\n LEFT JOIN labevents le\n ON le.subject_id = ie.subject_id AND le.hadm_id = ie.hadm_id\n AND le.charttime BETWEEN (DATETIME_SUB(ie.intime, INTERVAL '6' HOUR)) AND (DATETIME_ADD(ie.intime, INTERVAL '1' DAY))\n AND le.ITEMID in\n (\n -- comment is: LABEL | CATEGORY | FLUID | NUMBER OF ROWS IN LABEVENTS\n 50868,
-- ANION GAP | CHEMISTRY | BLOOD | 769895\n 50862, -- ALBUMIN | CHEMISTRY | BLOOD | 146697\n 51144, -- BANDS - hematology\n 50882, -- BICARBONATE | CHEMISTRY | BLOOD | 780733\n 50885, -- BILIRUBIN, TOTAL | CHEMISTRY | BLOOD | 238277\n 50912, -- CREATININE | CHEMISTRY | BLOOD | 797476\n 50902, -- CHLORIDE | CHEMISTRY | BLOOD | 795568\n 50806, -- CHLORIDE, WHOLE BLOOD | BLOOD GAS | BLOOD | 48187\n 50931, -- glucose | CHEMISTRY | BLOOD | 748981\n 50809, -- glucose | BLOOD GAS | BLOOD | 196734\n 51221, -- HEMATOCRIT | HEMATOLOGY | BLOOD | 881846\n 50810, -- HEMATOCRIT, CALCULATED | BLOOD GAS | BLOOD | 89715\n 51222, -- HEMOGLOBIN | HEMATOLOGY | BLOOD | 752523\n 50811, -- HEMOGLOBIN | BLOOD GAS | BLOOD | 89712\n 50813, -- LACTATE | BLOOD GAS | BLOOD | 187124\n 51265, -- PLATELET COUNT | HEMATOLOGY | BLOOD | 778444\n 50971, -- potassium | CHEMISTRY | BLOOD | 845825\n 50822, -- potassium, WHOLE BLOOD | BLOOD GAS | BLOOD | 192946\n 51275, -- PTT | HEMATOLOGY | BLOOD | 474937\n 51237, -- INR(PT) | HEMATOLOGY | BLOOD | 471183\n 51274, -- PT | HEMATOLOGY | BLOOD | 469090\n 50983, -- sodium | CHEMISTRY | BLOOD | 808489\n 50824, -- sodium, WHOLE BLOOD | BLOOD GAS | BLOOD | 71503\n 51006, -- UREA NITROGEN | CHEMISTRY | BLOOD | 791925\n 51301, -- WHITE BLOOD CELLS | HEMATOLOGY | BLOOD | 753301\n 51300 -- wbc COUNT | HEMATOLOGY | BLOOD | 2371\n )\n AND valuenum IS NOT null AND valuenum > 0 -- lab values cannot be 0 and cannot be negative\n) pvt\nGROUP BY pvt.subject_id, pvt.hadm_id, pvt.icustay_id\nORDER BY pvt.subject_id, pvt.hadm_id, pvt.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_labs\nowner to postgres;\n"
rrt_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_rrt;\ncreate materialized view mimic3.firstday_rrt\ntablespace pg_default\nas\n-- jing add head\n-- determines if patients received any dialysis during their stay\n\n-- Some example aggregate queries which summarize the data here..\n-- This query estimates 6.7% of ICU patients received rrt.\n -- select count(rrt.icustay_id) as numobs\n -- , sum(rrt) as numrrt\n -- , sum(case when rrt=1 then 1 else 0 end)*100.0 / count(rrt.icustay_id)\n -- as percent_rrt\n -- from rrt\n -- inner join icustays ie on rrt.icustay_id = ie.icustay_id\n -- inner join patients p\n -- on rrt.subject_id = p.subject_id\n -- and p.dob < ie.intime - interval '1' year\n -- inner join admissions adm\n -- on rrt.hadm_id = adm.hadm_id;\n\n-- This query estimates that 4.6% of first ICU stays received rrt.\n -- select\n -- count(rrt.icustay_id) as numobs\n -- , sum(rrt) as numrrt\n -- , sum(case when rrt=1 then 1 else 0 end)*100.0 / count(rrt.icustay_id)\n -- as percent_rrt\n -- from\n -- (\n -- select ie.icustay_id, rrt.rrt\n -- , ROW_NUMBER() over (partition by ie.subject_id order by ie.intime) rn\n -- from rrt\n -- inner join icustays ie\n -- on rrt.icustay_id = ie.icustay_id\n -- inner join patients p\n -- on rrt.subject_id = p.subject_id\n -- and p.dob < ie.intime - interval '1' year\n -- inner join admissions adm\n -- on rrt.hadm_id = adm.hadm_id\n -- ) rrt\n -- where rn = 1;\n\nwith cv as\n(\n select ie.icustay_id\n , max(\n case\n when ce.itemid in (152,148,149,146,147,151,150) and value is not null then 1\n when ce.itemid in (229,235,241,247,253,259,265,271) and value = 'Dialysis Line' then 1\n when ce.itemid = 582 and value in ('CAVH Start','CAVH D/C','CVVHD Start','CVVHD D/C','Hemodialysis st','Hemodialysis end') then 1\n else 0 end\n ) as rrt\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.itemid in\n (\n 152 -- \"Dialysis Type\";61449\n ,148 -- \"Dialysis Access Site\";60335\n ,149 -- \"Dialysis Access Type\";60030\n ,146 -- \"Dialysate Flow ml/hr\";57445\n ,147 -- \"Dialysate Infusing\";56605\n ,151 -- \"Dialysis Site Appear\";37345\n ,150 -- \"Dialysis Machine\";27472\n ,229 -- INV Line#1 [Type]\n ,235 -- INV Line#2 [Type]\n ,241 -- INV Line#3 [Type]\n ,247 -- INV Line#4 [Type]\n ,253 -- INV Line#5 [Type]\n ,259 -- INV Line#6 [Type]\n ,265 -- INV Line#7 [Type]\n ,271 -- INV Line#8 [Type]\n ,582 -- Procedures\n )\n and ce.value is not null\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where ie.dbsource = 'carevue'\n group by ie.icustay_id\n)\n, mv_ce as\n(\n select ie.icustay_id\n , 1 as rrt\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and itemid in\n (\n
-- Checkboxes\n 226118 -- | Dialysis Catheter placed in outside facility | Access Lines - Invasive | chartevents | Checkbox\n , 227357 -- | Dialysis Catheter Dressing Occlusive | Access Lines - Invasive | chartevents | Checkbox\n , 225725 -- | Dialysis Catheter Tip Cultured | Access Lines - Invasive | chartevents | Checkbox\n -- Numeric values\n , 226499 -- | Hemodialysis Output | Dialysis | chartevents | Numeric\n , 224154 -- | Dialysate Rate | Dialysis | chartevents | Numeric\n , 225810 -- | Dwell Time (Peritoneal Dialysis) | Dialysis | chartevents | Numeric\n , 227639 -- | Medication Added Amount #2 (Peritoneal Dialysis) | Dialysis | chartevents | Numeric\n , 225183 -- | Current Goal | Dialysis | chartevents | Numeric\n , 227438 -- | Volume not removed | Dialysis | chartevents | Numeric\n , 224191 -- | Hourly Patient Fluid Removal | Dialysis | chartevents | Numeric\n , 225806 -- | Volume In (PD) | Dialysis | chartevents | Numeric\n , 225807 -- | Volume Out (PD) | Dialysis | chartevents | Numeric\n , 228004 -- | Citrate (ACD-A) | Dialysis | chartevents | Numeric\n , 228005 -- | PBP (Prefilter) Replacement Rate | Dialysis | chartevents | Numeric\n , 228006 -- | Post Filter Replacement Rate | Dialysis | chartevents | Numeric\n , 224144 -- | Blood Flow (ml/min) | Dialysis | chartevents | Numeric\n , 224145 -- | Heparin Dose (per hour) | Dialysis | chartevents | Numeric\n , 224149 -- | Access Pressure | Dialysis | chartevents | Numeric\n , 224150 -- | Filter Pressure | Dialysis | chartevents | Numeric\n , 224151 -- | Effluent Pressure | Dialysis | chartevents | Numeric\n , 224152 -- | Return Pressure | Dialysis | chartevents | Numeric\n , 224153 -- | Replacement Rate | Dialysis | chartevents | Numeric\n , 224404 -- | ART Lumen Volume | Dialysis | chartevents | Numeric\n , 224406 -- | VEN Lumen Volume | Dialysis | chartevents | Numeric\n , 226457 -- | Ultrafiltrate Output | Dialysis | chartevents | Numeric\n )\n and valuenum > 0 -- also ensures it's not null\n group by ie.icustay_id\n)\n, mv_ie as\n(\n select ie.icustay_id\n , 1 as rrt\n FROM icustays ie\n inner join inputevents_mv tt\n on ie.icustay_id = tt.icustay_id\n and tt.starttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and itemid in\n (\n 227536
--\tKCl (CRRT)\tMedications\tinputevents_mv\tSolution\n , 227525 --\tCalcium Gluconate (CRRT)\tMedications\tinputevents_mv\tSolution\n )\n and amount > 0 -- also ensures it's not null\n group by ie.icustay_id\n)\n, mv_de as\n(\n select ie.icustay_id\n , 1 as rrt\n FROM icustays ie\n inner join datetimeevents tt\n on ie.icustay_id = tt.icustay_id\n and tt.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and itemid in\n (\n -- TODO: unsure how to handle \"Last dialysis\"\n -- 225128 -- | Last dialysis | Adm History/FHPA | datetimeevents | Date time\n 225318 -- | Dialysis Catheter Cap Change | Access Lines - Invasive | datetimeevents | Date time\n , 225319 -- | Dialysis Catheter Change over Wire Date | Access Lines - Invasive | datetimeevents | Date time\n , 225321 -- | Dialysis Catheter Dressing Change | Access Lines - Invasive | datetimeevents | Date time\n , 225322 -- | Dialysis Catheter Insertion Date | Access Lines - Invasive | datetimeevents | Date time\n , 225324 -- | Dialysis CatheterTubing Change | Access Lines - Invasive | datetimeevents | Date time\n )\n group by ie.icustay_id\n)\n, mv_pe as\n(\n select ie.icustay_id\n , 1 as rrt\n FROM icustays ie\n inner join procedureevents_mv tt\n on ie.icustay_id = tt.icustay_id\n and tt.starttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and itemid in\n (\n 225441 -- | Hemodialysis | 4-Procedures | procedureevents_mv | Process\n , 225802 -- | Dialysis - CRRT | Dialysis | procedureevents_mv | Process\n , 225803 -- | Dialysis - CVVHD | Dialysis | procedureevents_mv | Process\n , 225805 -- | Peritoneal Dialysis | Dialysis | procedureevents_mv | Process\n , 224270 -- | Dialysis Catheter | Access Lines - Invasive | procedureevents_mv | Process\n , 225809 -- | Dialysis - CVVHDF | Dialysis | procedureevents_mv | Process\n , 225955 -- | Dialysis - SCUF | Dialysis | procedureevents_mv | Process\n , 225436 -- | CRRT Filter Change | Dialysis | procedureevents_mv | Process\n )\n group by ie.icustay_id\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n , case\n when cv.RRT = 1 then 1\n when mv_ce.RRT = 1 then 1\n when mv_ie.RRT = 1 then 1\n when mv_de.RRT = 1 then 1\n when mv_pe.RRT = 1 then 1\n else 0\n end as rrt\nFROM icustays ie\nleft join cv\n on ie.icustay_id = cv.icustay_id\nleft join mv_ce\n on ie.icustay_id = mv_ce.icustay_id\nleft join mv_ie\n on ie.icustay_id = mv_ie.icustay_id\nleft join mv_de\n on ie.icustay_id = mv_de.icustay_id\nleft join mv_pe\n on ie.icustay_id = mv_pe.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_rrt\nowner to postgres;\n"
urine_output_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_urine_output;\ncreate materialized view mimic3.firstday_urine_output\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Purpose: Create a view of the urine output for each ICUSTAY_ID over the first 24 hours.\n-- ------------------------------------------------------------------\n\nselect\n -- patient identifiers\n ie.subject_id, ie.hadm_id, ie.icustay_id\n\n -- volumes associated with urine output ITEMIDs\n , sum(\n -- we consider input of GU irrigant as a negative volume\n case\n when oe.itemid = 227488 and oe.value > 0 then -1*oe.value\n else oe.value\n end) as urineoutput\nFROM icustays ie\n-- Join to the outputevents table to get urine output\nleft join outputevents oe\n-- join on all patient identifiers\non ie.subject_id = oe.subject_id and ie.hadm_id = oe.hadm_id and ie.icustay_id = oe.icustay_id\n-- and ensure the data occurs during the first day\nand oe.charttime between ie.intime and (DATETIME_ADD(ie.intime, INTERVAL '1' DAY)) -- first ICU day\nwhere itemid in\n(\n-- these are the most frequently occurring urine output observations in CareVue\n40055, -- \"Urine Out Foley\"\n43175, -- \"Urine .\"\n40069, -- \"Urine Out Void\"\n40094, -- \"Urine Out Condom Cath\"\n40715, -- \"Urine Out Suprapubic\"\n40473, -- \"Urine Out IleoConduit\"\n40085, -- \"Urine Out Incontinent\"\n40057, -- \"Urine Out Rt Nephrostomy\"\n40056, -- \"Urine Out Lt Nephrostomy\"\n40405, -- \"Urine Out Other\"\n40428, -- \"Urine Out Straight Cath\"\n40086,--\tUrine Out Incontinent\n40096, -- \"Urine Out Ureteral Stent #1\"\n40651, -- \"Urine Out Ureteral Stent #2\"\n\n-- these are the most frequently occurring urine output observations in MetaVision\n226559, -- \"Foley\"\n226560, -- \"Void\"\n226561, -- \"Condom Cath\"\n226584, -- \"Ileoconduit\"\n226563, -- \"Suprapubic\"\n226564, -- \"R Nephrostomy\"\n226565, -- \"L Nephrostomy\"\n226567, --\tStraight Cath\n226557, -- R Ureteral Stent\n226558, -- L Ureteral Stent\n227488, -- GU Irrigant Volume In\n227489 -- GU Irrigant/Urine Volume Out\n)\ngroup by ie.subject_id, ie.hadm_id, ie.icustay_id\norder by ie.subject_id, ie.hadm_id, ie.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_urine_output\nowner to postgres;\n"
ventilation_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_ventilation;\ncreate materialized view mimic3.firstday_ventilation\ntablespace pg_default\nas\n-- jing add head\n-- Determines if a patient is ventilated on the first day of their ICU stay.\n-- Creates a table with the result.\n-- Requires the durations_ventilation_durations table, generated by ../ventilation-durations.sql\n\nselect\n ie.subject_id, ie.hadm_id, ie.icustay_id\n -- if vd.icustay_id is not null, then they have a valid ventilation event\n -- in this case, we say they are ventilated\n -- otherwise, they are not\n , max(case\n when vd.icustay_id is not null then 1\n else 0 end) as vent\nFROM icustays ie\nleft join durations_ventilation_durations vd\n on ie.icustay_id = vd.icustay_id\n and\n (\n -- ventilation duration overlaps with ICU admission -> vented on admission\n (vd.starttime <= ie.intime and vd.endtime >= ie.intime)\n -- ventilation started during the first day\n OR (vd.starttime >= ie.intime and vd.starttime <= DATETIME_ADD(ie.intime, INTERVAL '1' DAY))\n )\ngroup by ie.subject_id, ie.hadm_id, ie.icustay_id\norder by ie.subject_id, ie.hadm_id, ie.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_ventilation\nowner to postgres;\n"
vitals_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_vitals;\ncreate materialized view mimic3.firstday_vitals\ntablespace pg_default\nas\n-- jing add head\n-- This query pivots the vital signs for the first 24 hours of a patient's stay\n-- Vital signs include heart rate, blood pressure, respiration rate, and temperature\n\nSELECT pvt.subject_id, pvt.hadm_id, pvt.icustay_id\n\n-- Easier names\n, min(case when VitalID = 1 then valuenum ELSE NULL END) AS heartrate_min\n, max(case when VitalID = 1 then valuenum ELSE NULL END) AS heartrate_max\n, avg(case when VitalID = 1 then valuenum ELSE NULL END) AS heartrate_mean\n, min(case when VitalID = 2 then valuenum ELSE NULL END) AS sysbp_min\n, max(case when VitalID = 2 then valuenum ELSE NULL END) AS sysbp_max\n, avg(case when VitalID = 2 then valuenum ELSE NULL END) AS sysbp_mean\n, min(case when VitalID = 3 then valuenum ELSE NULL END) AS diasbp_min\n, max(case when VitalID = 3 then valuenum ELSE NULL END) AS diasbp_max\n, avg(case when VitalID = 3 then valuenum ELSE NULL END) AS diasbp_mean\n, min(case when VitalID = 4 then valuenum ELSE NULL END) AS meanbp_min\n, max(case when VitalID = 4 then valuenum ELSE NULL END) AS meanbp_max\n, avg(case when VitalID = 4 then valuenum ELSE NULL END) AS meanbp_mean\n, min(case when VitalID = 5 then valuenum ELSE NULL END) AS resprate_min\n, max(case when VitalID = 5 then valuenum ELSE NULL END) AS resprate_max\n, avg(case when VitalID = 5 then valuenum ELSE NULL END) AS resprate_mean\n, min(case when VitalID = 6 then valuenum ELSE NULL END) AS tempc_min\n, max(case when VitalID = 6 then valuenum ELSE NULL END) AS tempc_max\n, avg(case when VitalID = 6 then valuenum ELSE NULL END) AS tempc_mean\n, min(case when VitalID = 7 then valuenum ELSE NULL END) AS spo2_min\n, max(case when VitalID = 7 then valuenum ELSE NULL END) AS spo2_max\n, avg(case when VitalID = 7 then valuenum ELSE NULL END) AS spo2_mean\n, min(case when VitalID = 8 then valuenum ELSE NULL END) AS glucose_min\n, max(case when VitalID = 8 then valuenum ELSE NULL END) AS glucose_max\n, avg(case when VitalID = 8 then valuenum ELSE NULL END) AS glucose_mean\n\nFROM (\n select ie.subject_id, ie.hadm_id, ie.icustay_id\n , case\n when itemid in (211,220045) and valuenum > 0 and valuenum < 300 then 1 -- HeartRate\n when itemid in (51,442,455,6701,220179,220050) and valuenum > 0 and valuenum < 400 then 2 -- SysBP\n when itemid in (8368,8440,8441,8555,220180,220051) and valuenum > 0 and valuenum < 300 then 3 -- DiasBP\n when itemid in (456,52,6702,443,220052,220181,225312) and valuenum > 0 and valuenum < 300 then 4
-- MeanBP\n when itemid in (615,618,220210,224690) and valuenum > 0 and valuenum < 70 then 5 -- RespRate\n when itemid in (223761,678) and valuenum > 70 and valuenum < 120 then 6 -- tempF, converted to degC in valuenum call\n when itemid in (223762,676) and valuenum > 10 and valuenum < 50 then 6 -- tempC\n when itemid in (646,220277) and valuenum > 0 and valuenum <= 100 then 7 -- SpO2\n when itemid in (807,811,1529,3745,3744,225664,220621,226537) and valuenum > 0 then 8 -- glucose\n\n else null end as vitalid\n -- convert F to C\n , case when itemid in (223761,678) then (valuenum-32)/1.8 else valuenum end as valuenum\n\n from icustays ie\n left join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, interval '1 DAY' * ('1'))\n and datetime_diff(ce.charttime, ie.intime, 'SECOND') > 0\n and datetime_diff(ce.charttime, ie.intime, 'HOUR') <= 24\n -- exclude rows marked as error\n and (ce.error IS NULL or ce.error = 0)\n where ce.itemid in\n (\n -- HEART RATE\n 211, --\\\"Heart Rate\\\"\n 220045, --\\\"Heart Rate\\\"\n\n -- Systolic/diastolic\n\n 51, --\tArterial BP [Systolic]\n 442, --\tManual BP [Systolic]\n 455, --\tNBP [Systolic]\n 6701, --\tArterial BP #2 [Systolic]\n 220179, --\tNon Invasive Blood Pressure systolic\n 220050, --\tArterial Blood Pressure systolic\n\n 8368, --\tArterial BP [Diastolic]\n 8440, --\tManual BP [Diastolic]\n 8441, --\tNBP [Diastolic]\n 8555, --\tArterial BP #2 [Diastolic]\n 220180, --\tNon Invasive Blood Pressure diastolic\n 220051, --\tArterial Blood Pressure diastolic\n\n\n -- MEAN ARTERIAL PRESSURE\n 456, --\\\"NBP Mean\\\"\n 52, --\\\"Arterial BP Mean\\\"\n 6702, --\tArterial BP Mean #2\n 443, --\tManual BP Mean(calc)\n 220052, --\\\"Arterial Blood Pressure mean\\\"\n 220181, --\\\"Non Invasive Blood Pressure mean\\\"\n 225312, --\\\"ART BP mean\\\"\n\n -- RESPIRATORY RATE\n 618,--\tRespiratory Rate\n 615,--\tResp Rate (Total)\n 220210,--\tRespiratory Rate\n 224690, --\tRespiratory Rate (Total)\n\n\n -- SPO2, peripheral\n 646, 220277,\n\n -- glucose, both lab and fingerstick\n 807,--\tFingerstick glucose\n 811,--\tGlucose (70-105)\n 1529,--\tGlucose\n 3745,--\tBloodGlucose\n 3744,--\tBlood glucose\n 225664,--\tGlucose finger stick\n 220621,--\tGlucose (serum)\n 226537,--\tGlucose (whole blood)\n\n -- tempERATURE\n 223762, -- \\\"Temperature Celsius\\\"\n 676,\t-- \\\"Temperature C\\\"\n 223761, -- \\\"Temperature Fahrenheit\\\"\n 678 --\t\\\"Temperature F\\\"\n\n )\n) pvt\ngroup by pvt.subject_id, pvt.hadm_id, pvt.icustay_id\norder by pvt.subject_id, pvt.hadm_id, pvt.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_vitals\nowner to postgres;"
weight_first_day <-"SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS firstday_weight;\ncreate materialized view mimic3.firstday_weight\ntablespace pg_default\nas\n-- jing add head\n-- This query extracts weights for adult ICU patients on their first ICU day.\n-- It does *not* use any information after the first ICU day, as weight is\n-- sometimes used to monitor fluid balance.\n\n-- ** Requires the echodata view, generated by concepts/echo-data.sql\n\nwith ce as\n(\n SELECT\n c.icustay_id\n -- we take the avg value from roughly first day\n -- TODO: eliminate obvious outliers if there is a reasonable weight\n -- (e.g. weight of 180kg and 90kg would remove 180kg instead of taking the median)\n , AVG(VALUENUM) as Weight_Admit\n FROM chartevents c\n inner join icustays ie\n on c.icustay_id = ie.icustay_id\n and c.charttime <= DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and c.charttime > DATETIME_SUB(ie.intime, INTERVAL '1' DAY) -- some fuzziness for admit time\n WHERE c.valuenum IS NOT NULL\n AND c.itemid in (762,226512) -- Admit Wt\n AND c.valuenum != 0\n -- exclude rows marked as error\n AND (c.error IS NULL OR c.error = 0)\n group by c.icustay_id\n)\n, dwt as\n(\n SELECT\n c.icustay_id\n , AVG(VALUENUM) as Weight_Daily\n FROM chartevents c\n INNER JOIN icustays ie\n on c.icustay_id = ie.icustay_id\n and c.charttime <= DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n and c.charttime > DATETIME_SUB(ie.intime, INTERVAL '1' DAY) -- some fuzziness for admit time\n WHERE c.valuenum IS NOT NULL\n AND c.itemid in (763,224639) -- Daily Weight\n AND c.valuenum != 0\n -- exclude rows marked as error\n AND (c.error IS NULL OR c.error = 0)\n group by c.icustay_id\n)\n-- we split in-hospital/out of hospital echoes as we would like to prioritize in-hospital data\n, echo_hadm as\n(\n select\n ie.icustay_id\n , 0.453592*AVG(weight) as Weight_EchoInHosp\n from echo_data ec\n inner join icustays ie\n on ec.hadm_id = ie.hadm_id\n and ec.charttime < DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where\n ec.HADM_ID is not null\n and ec.weight is not null\n group by ie.icustay_id\n)\n, echo_nohadm as\n(\n select\n ie.icustay_id\n , 0.453592*AVG(weight) as Weight_EchoPreHosp\n from echo_data ec\n inner join icustays ie\n on ie.subject_id = ec.subject_id\n and ie.intime < DATETIME_ADD(ec.charttime, INTERVAL '1' MONTH)\n and ie.intime > ec.charttime\n where\n ec.HADM_ID is null\n and ec.weight is not null\n group by ie.icustay_id\n)\nselect\n ie.icustay_id\n , round(cast(\n case\n when ce.icustay_id is not null\n then ce.Weight_Admit\n when dwt.icustay_id is not null\n then dwt.Weight_Daily\n when eh.icustay_id is not null\n then eh.Weight_EchoInHosp\n when enh.icustay_id is not null\n then enh.Weight_EchoPreHosp\n else null end\n as numeric), 2)\n as weight\n\n -- components\n , ce.weight_admit\n , dwt.weight_daily\n , eh.weight_echoinhosp\n , enh.weight_echoprehosp\n\nFROM icustays ie\n\n-- filter to only adults\ninner join patients pat\n on ie.subject_id = pat.subject_id\n and ie.intime > DATETIME_ADD(pat.dob, INTERVAL '1' YEAR)\n\n-- admission weight\nleft join ce\n on ie.icustay_id = ce.icustay_id\n\n-- daily weights\nleft join dwt\n on ie.icustay_id = dwt.icustay_id\n\n-- in-hospital echo weight\nleft join echo_hadm eh\n on ie.icustay_id = eh.icustay_id\n\n-- pre-hospitalization echo weights\nleft join echo_nohadm enh\n on ie.icustay_id = enh.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.firstday_weight\nowner to postgres;\n"
# 5 fluid_balance'------------------------
colloid_bolus <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS fluid_balance_colloid_bolus;\ncreate materialized view mimic3.fluid_balance_colloid_bolus\ntablespace pg_default\nas\n-- jing add head\n-- received colloid before admission\n-- 226365 -- OR Colloid Intake\n-- 226376 -- PACU Colloid Intake\n\nwith t1 as\n(\n select\n mv.icustay_id\n , mv.starttime as charttime\n -- standardize the units to millilitres\n -- also metavision has floating point precision.. but we only care down to the mL\n , round(case\n when mv.amountuom = 'L'\n then mv.amount * 1000.0\n when mv.amountuom = 'ml'\n then mv.amount\n else null end) as amount\n from inputevents_mv mv\n where mv.itemid in\n (\n 220864, -- Albumin 5% 7466 132 7466\n 220862, -- Albumin 25% 9851 174 9851\n 225174, -- Hetastarch (Hespan) 6% 82 1 82\n 225795, -- Dextran 40 38 3 38\n 225796 -- Dextran 70\n -- below ITEMIDs not in use\n -- 220861 | Albumin (Human) 20%\n -- 220863 | Albumin (Human) 4%\n )\n and mv.statusdescription != 'Rewritten'\n and\n -- in MetaVision, these ITEMIDs never appear with a null rate\n -- so it is sufficient to check the rate is > 100\n (\n (mv.rateuom = 'mL/hour' and mv.rate > 100)\n OR (mv.rateuom = 'mL/min' and mv.rate > (100/60.0))\n OR (mv.rateuom = 'mL/kg/hour' and (mv.rate*mv.patientweight) > 100)\n )\n)\n, t2 as\n(\n select\n cv.icustay_id\n , cv.charttime\n -- carevue always has units in millilitres (or null)\n , round(cv.amount) as amount\n from inputevents_cv cv\n where cv.itemid in\n (\n 30008 -- Albumin 5%\n ,30009 -- Albumin 25%\n ,42832
-- albumin 12.5%\n ,40548 -- ALBUMIN\n ,45403 -- albumin\n ,44203 -- Albumin 12.5%\n ,30181 -- Serum Albumin 5%\n ,46564 -- Albumin\n ,43237 -- 25% Albumin\n ,43353 -- Albumin (human) 25%\n\n ,30012 -- Hespan\n ,46313 -- 6% Hespan\n\n ,30011 -- Dextran 40\n ,30016 -- Dextrose 10%\n ,42975 -- DEXTRAN DRIP\n ,42944 -- dextran\n ,46336 -- 10% Dextran 40/D5W\n ,46729 -- Dextran\n ,40033 -- DEXTRAN\n ,45410 -- 10% Dextran 40\n ,42731 -- Dextran40 10%\n )\n and cv.amount > 100\n and cv.amount < 2000\n)\n-- some colloids are charted in chartevents\n, t3 as\n(\n select\n ce.icustay_id\n , ce.charttime\n -- carevue always has units in millilitres (or null)\n , round(ce.valuenum) as amount\n from chartevents ce\n where ce.itemid in\n (\n 2510
-- DEXTRAN LML 10%\n , 3087 -- DEXTRAN 40 10%\n , 6937 -- Dextran\n , 3087 -- DEXTRAN 40 10%\n , 3088 -- DEXTRAN 40%\n )\n and ce.valuenum is not null\n and ce.valuenum > 100\n and ce.valuenum < 2000\n)\nselect\n icustay_id\n , charttime\n , sum(amount) as colloid_bolus\nfrom t1\n-- just because the rate was high enough, does *not* mean the final amount was\nwhere amount > 100\ngroup by t1.icustay_id, t1.charttime\nUNION\nselect\n icustay_id\n , charttime\n , sum(amount) as colloid_bolus\nfrom t2\ngroup by t2.icustay_id, t2.charttime\nUNION\nselect\n icustay_id\n , charttime\n , sum(amount) as colloid_bolus\nfrom t3\ngroup by t3.icustay_id, t3.charttime\norder by icustay_id, charttime;\n-- jing add tail\nalter table mimic3.fluid_balance_colloid_bolus\nowner to postgres;"
crystalloid_bolus <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS fluid_balance_crystalloid_bolus;\ncreate materialized view mimic3.fluid_balance_crystalloid_bolus\ntablespace pg_default\nas\n-- jing add head\nwith t1 as\n(\n select\n mv.icustay_id\n , mv.starttime as charttime\n -- standardize the units to millilitres\n -- also metavision has floating point precision.. but we only care down to the mL\n , round(case\n when mv.amountuom = 'L'\n then mv.amount * 1000.0\n when mv.amountuom = 'ml'\n then mv.amount\n else null end) as amount\n from inputevents_mv mv\n where mv.itemid in\n (\n -- 225943 Solution\n 225158, -- NaCl 0.9%\n 225828, -- LR\n 225944, -- Sterile Water\n 225797, -- Free Water\n 225159, -- NaCl 0.45%\n -- 225161, -- NaCl 3% (Hypertonic Saline)\n 225823, -- D5 1/2NS\n 225825, -- D5NS\n 225827, -- D5LR\n 225941, -- D5 1/4NS\n 226089 -- Piggyback\n )\n and mv.statusdescription != 'Rewritten'\n and\n -- in MetaVision, these ITEMIDs appear with a null rate IFF endtime=starttime + 1 minute\n -- so it is sufficient to:\n -- (1) check the rate is > 240 if it exists or\n -- (2) ensure the rate is null and amount > 240 ml\n (\n (mv.rate is not null and mv.rateuom = 'mL/hour' and mv.rate > 248)\n OR (mv.rate is not null and mv.rateuom = 'mL/min' and mv.rate > (248/60.0))\n OR (mv.rate is null and mv.amountuom = 'L' and mv.amount > 0.248)\n OR (mv.rate is null and mv.amountuom = 'ml' and mv.amount > 248)\n )\n)\n, t2 as\n(\n select\n cv.icustay_id\n , cv.charttime\n -- carevue always has units in millilitres\n , round(cv.amount) as amount\n from inputevents_cv cv\n where cv.itemid in\n (\n 30015 -- \"D5/.45NS\" -- mixed colloids and crystalloids\n , 30018 -- .9% Normal Saline\n , 30020
-- .45% Normal Saline\n , 30021 -- Lactated Ringers\n , 30058 -- Free Water Bolus\n , 30060 -- D5NS\n , 30061 -- D5RL\n , 30063 -- IV Piggyback\n , 30065 -- Sterile Water\n -- , 30143 -- 3% Normal Saline\n , 30159 -- D5 Ringers Lact.\n , 30160 -- D5 Normal Saline\n , 30169 -- Sterile H20_GU\n , 30190 -- NS .9%\n , 40850 -- ns bolus\n , 41491 -- fluid bolus\n , 42639 -- bolus\n , 42187 -- free h20\n , 43819 -- 1:1 NS Repletion.\n , 41430 -- free water boluses\n , 40712 -- free H20\n , 44160 -- BOLUS\n , 42383 -- cc for cc replace\n , 42297 -- Fluid bolus\n , 42453 -- Fluid Bolus\n , 40872 -- free water\n , 41915 -- FREE WATER\n , 41490 -- NS bolus\n , 46501 -- H2O Bolus\n , 45045 -- WaterBolus\n , 41984 -- FREE H20\n , 41371
-- ns fluid bolus\n , 41582 -- free h20 bolus\n , 41322 -- rl bolus\n , 40778 -- Free H2O\n , 41896 -- ivf boluses\n , 41428 -- ns .9% bolus\n , 43936 -- FREE WATER BOLUSES\n , 44200 -- FLUID BOLUS\n , 41619 -- frfee water boluses\n , 40424 -- free H2O\n , 41457 -- Free H20 intake\n , 41581 -- Water bolus\n , 42844 -- NS fluid bolus\n , 42429 -- Free water\n , 41356 -- IV Bolus\n , 40532 -- FREE H2O\n , 42548 -- NS Bolus\n , 44184 -- LR Bolus\n , 44521 -- LR bolus\n , 44741 -- NS FLUID BOLUS\n , 44126 -- fl bolus\n , 44110 -- RL BOLUS\n , 44633 -- ns boluses\n , 44983 -- Bolus NS\n , 44815 -- LR BOLUS\n , 43986 -- iv bolus\n , 45079 -- 500 cc ns bolus\n , 46781 -- lr bolus\n , 45155 -- ns cc/cc replacement\n , 43909 -- H20 BOlus\n , 41467 -- NS IV bolus\n , 44367 -- LR\n , 41743 -- water bolus\n , 40423 -- Bolus\n , 44263 -- fluid bolus ns\n , 42749 -- fluid bolus NS\n , 45480 -- 500cc ns bolus\n , 44491 -- .9NS bolus\n , 41695 -- NS fluid boluses\n , 46169 -- free water bolus.\n , 41580 -- free h2o bolus\n , 41392 -- ns b\n , 45989 -- NS Fluid Bolus\n , 45137 -- NS cc/cc\n , 45154 -- Free H20 bolus\n , 44053 -- normal saline bolus\n , 41416 -- free h2o boluses\n , 44761 -- Free H20\n , 41237 -- ns fluid boluses\n , 44426 -- bolus ns\n , 43975 -- FREE H20 BOLUSES\n , 44894 -- N/s 500 ml bolus\n , 41380 -- nsbolus\n , 42671 -- free h2o\n )\n and cv.amount > 248\n and cv.amount <= 2000\n and cv.amountuom = 'ml'\n)\nselect\n icustay_id\n , charttime\n , sum(amount) as crystalloid_bolus\nfrom t1\n-- just because the rate was high enough, does *not* mean the final amount was\nwhere amount > 248\ngroup by t1.icustay_id, t1.charttime\nUNION\nselect\n icustay_id\n , charttime\n , sum(amount) as crystalloid_bolus\nfrom t2\ngroup by t2.icustay_id, t2.charttime\norder by icustay_id, charttime;\n-- jing add tail\nalter table mimic3.fluid_balance_crystalloid_bolus\nowner to postgres;"
ffp_transfusion <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS fluid_balance_ffp_transfusion;\ncreate materialized view mimic3.fluid_balance_ffp_transfusion\ntablespace pg_default\nas\n-- jing add head\n-- Retrieves instances of fresh frozen plasma transfusions\nWITH raw_ffp AS (\n SELECT\n CASE\n WHEN amount IS NOT NULL THEN amount\n WHEN stopped IS NOT NULL THEN 0\n -- impute 200 mL when unit is not documented\n -- this is an approximation which holds ~90% of the time\n ELSE 200\n END AS amount\n , amountuom\n , icustay_id\n , charttime\n FROM inputevents_cv\n WHERE itemid IN\n (\n 30005, -- Fresh Frozen Plasma\n 30180 -- Fresh Froz Plasma\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n UNION ALL\n SELECT amount\n , amountuom\n , icustay_id\n , endtime AS charttime\n FROM inputevents_mv\n WHERE itemid in\n (\n 220970 -- Fresh Frozen Plasma\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n),\npre_icu_ffp as (\n SELECT\n sum(amount) as amount, icustay_id\n FROM inputevents_cv\n WHERE itemid IN (\n 44172, -- FFP GTT \n 44236, -- E.R. FFP \n 46410, -- angio FFP\n 46418, -- ER ffp\n 46684, -- ER FFP\n 44819, -- FFP ON FARR 2\n 46530, -- Floor FFP \n 44044, -- FFP Drip\n 46122, -- ER in FFP\n 45669, -- ED FFP\n 42323 -- er ffp\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n GROUP BY icustay_id\n UNION ALL\n SELECT\n sum(amount) as amount, icustay_id\n FROM inputevents_mv\n WHERE itemid IN (\n 227072 -- PACU FFP Intake\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n GROUP BY icustay_id\n),\ncumulative AS (\n SELECT\n sum(amount) over (PARTITION BY icustay_id ORDER BY charttime DESC) AS amount\n , amountuom\n , icustay_id\n , charttime\n , datetime_diff(lag(charttime) over (PARTITION BY icustay_id ORDER BY charttime ASC), charttime,'HOUR') AS delta\n FROM raw_ffp\n)\n-- We consider any transfusions started within 1 hr of the last one\n
-- to be part of the same event\nSELECT\n cm.icustay_id\n , cm.charttime\n , ROUND(CAST(cm.amount AS numeric) - CASE\n WHEN ROW_NUMBER() OVER w = 1 THEN CAST(0 AS numeric)\n ELSE cast(lag(cm.amount) OVER w AS numeric)\n END, 2) AS amount\n , ROUND(CAST(cm.amount AS numeric) + CASE\n WHEN pre.amount IS NULL THEN CAST(0 AS numeric)\n ELSE CAST(pre.amount AS numeric)\n END, 2) AS totalamount\n , cm.amountuom\nFROM cumulative AS cm\nLEFT JOIN pre_icu_ffp AS pre\n USING (icustay_id)\nWHERE delta IS NULL OR delta < -1\nWINDOW w AS (PARTITION BY cm.icustay_id ORDER BY cm.charttime DESC)\nORDER BY icustay_id, charttime;\n-- jing add tail\nalter table mimic3.fluid_balance_ffp_transfusion\nowner to postgres;"
rbc_transfusion <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS fluid_balance_rbc_transfusion;\ncreate materialized view mimic3.fluid_balance_rbc_transfusion\ntablespace pg_default\nas\n-- jing add head\n-- Retrieves instances of red blood cell transfusions\nwith raw_rbc as (\n SELECT\n CASE\n WHEN amount IS NOT NULL THEN amount\n WHEN stopped IS NOT NULL THEN 0\n -- impute 375 mL when unit is not documented\n ELSE 375\n END AS amount\n , amountuom\n , icustay_id\n , charttime\n FROM inputevents_cv\n WHERE itemid IN\n (\n 30179, -- PRBC's\n 30001, -- Packed RBC's\n 30004 -- Washed PRBC's\n )\n AND icustay_id IS NOT NULL\n UNION ALL\n SELECT amount\n , amountuom\n , icustay_id\n , endtime AS charttime\n FROM inputevents_mv\n WHERE itemid in\n (\n 225168 -- Packed Red Blood Cells\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n),\npre_icu_rbc as (\n SELECT\n sum(amount) as amount, icustay_id\n FROM inputevents_cv\n WHERE itemid IN (\n 42324, -- er prbc\n 42588, -- VICU PRBC\n 42239, -- CC7 PRBC\n 46407, -- ED PRBC\n 46612, -- E.R. prbc\n 46124, -- er in prbc\n 42740 -- prbc in er\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n GROUP BY icustay_id\n UNION ALL\n SELECT\n sum(amount) as amount, icustay_id\n FROM inputevents_mv\n WHERE itemid IN (\n 227070 -- PACU Packed RBC Intake\n )\n AND amount > 0\n AND icustay_id IS NOT NULL\n GROUP BY icustay_id\n),\ncumulative AS (\n SELECT\n sum(amount) over (PARTITION BY icustay_id ORDER BY charttime DESC) AS amount\n , amountuom\n , icustay_id\n , charttime\n , datetime_diff(lag(charttime) over (PARTITION BY icustay_id ORDER BY charttime ASC), charttime,'HOUR') AS delta\n FROM raw_rbc\n)\n
-- We consider any transfusions started within 1 hr of the last one\n-- to be part of the same event\nSELECT\n cm.icustay_id\n , cm.charttime\n , ROUND(CAST(cm.amount AS numeric) - CASE\n WHEN ROW_NUMBER() OVER w = 1 THEN CAST(0 AS numeric)\n ELSE CAST(lag(cm.amount) OVER w AS numeric)\n END, 2) AS amount\n , ROUND(CAST(cm.amount AS numeric) + CASE\n WHEN CAST(pre.amount AS numeric) IS NULL THEN CAST(0 AS numeric)\n ELSE CAST(pre.amount AS numeric)\n END, 2) AS totalamount\n , cm.amountuom\nFROM cumulative AS cm\nLEFT JOIN pre_icu_rbc AS pre\n USING (icustay_id)\nWHERE delta IS NULL OR delta < -1\nWINDOW w AS (PARTITION BY cm.icustay_id ORDER BY cm.charttime DESC)\nORDER BY icustay_id, charttime;\n-- jing add tail\nalter table mimic3.fluid_balance_rbc_transfusion\nowner to postgres;"
urine_output <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS fluid_balance_urine_output;\ncreate materialized view mimic3.fluid_balance_urine_output\ntablespace pg_default\nas\n-- jing add head\n-- First we drop the table if it exists\nselect oe.icustay_id, oe.charttime\n, SUM(\n -- we consider input of GU irrigant as a negative volume\n case when oe.itemid = 227488 then -1*value\n else value end\n ) as value\nfrom outputevents oe\nwhere oe.itemid in\n(\n -- these are the most frequently occurring urine output observations in CareVue\n 40055, -- \"Urine Out Foley\"\n 43175, -- \"Urine .\"\n 40069, -- \"Urine Out Void\"\n 40094, -- \"Urine Out Condom Cath\"\n 40715, -- \"Urine Out Suprapubic\"\n 40473, -- \"Urine Out IleoConduit\"\n 40085, -- \"Urine Out Incontinent\"\n 40057, -- \"Urine Out Rt Nephrostomy\"\n 40056, -- \"Urine Out Lt Nephrostomy\"\n 40405, -- \"Urine Out Other\"\n 40428, -- \"Urine Out Straight Cath\"\n 40086,-- Urine Out Incontinent\n 40096, -- \"Urine Out Ureteral Stent #1\"\n 40651, -- \"Urine Out Ureteral Stent #2\"\n\n -- these are the most frequently occurring urine output observations in MetaVision\n 226559, -- \"Foley\"\n 226560, -- \"Void\"\n 226561, -- \"Condom Cath\"\n 226584, -- \"Ileoconduit\"\n 226563, -- \"Suprapubic\"\n 226564, -- \"R Nephrostomy\"\n 226565, -- \"L Nephrostomy\"\n 226567, -- Straight Cath\n 226557, -- R Ureteral Stent\n 226558, -- L Ureteral Stent\n 227488, -- GU Irrigant Volume In\n 227489 -- GU Irrigant/Urine Volume Out\n)\nand oe.value < 5000 -- sanity check on urine value\nand oe.icustay_id is not null\ngroup by icustay_id, charttime;\n-- jing add tail\nalter table mimic3.fluid_balance_urine_output\nowner to postgres;"
# 3 sepsis-------
angus <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS sepsis_angus;\ncreate materialized view mimic3.sepsis_angus\ntablespace pg_default\nas\n-- jing add head\n-- ICD-9 codes for sepsis_angus criteria of sepsis\n\n-- sepsis_angus et al, 2001. Epidemiology of severe sepsis in the United States\n-- http://www.ncbi.nlm.nih.gov/pubmed/11445675\n\n-- Case selection and definitions\n-- To identify cases with severe sepsis, we selected all acute care\n-- hospitalizations with ICD-9-CM codes for both:\n-- (a) a bacterial or fungal infectious process AND\n-- (b) a diagnosis of acute organ dysfunction (Appendix 2).\n\n-- ICD-9 codes for infection - as sourced from Appendix 1 of above paper\nWITH infection_group AS\n(\n SELECT subject_id, hadm_id,\n CASE\n WHEN SUBSTR(icd9_code,1,3) IN ('001','002','003','004','005','008',\n '009','010','011','012','013','014','015','016','017','018',\n '020','021','022','023','024','025','026','027','030','031',\n '032','033','034','035','036','037','038','039','040','041',\n '090','091','092','093','094','095','096','097','098','100',\n '101','102','103','104','110','111','112','114','115','116',\n '117','118','320','322','324','325','420','421','451','461',\n '462','463','464','465','481','482','485','486','494','510',\n '513','540','541','542','566','567','590','597','601','614',\n '615','616','681','682','683','686','730') THEN 1\n WHEN SUBSTR(icd9_code,1,4) IN ('5695','5720','5721','5750','5990','7110',\n '7907','9966','9985','9993') THEN 1\n WHEN SUBSTR(icd9_code,1,5) IN ('49121','56201','56203','56211','56213',\n '56983') THEN 1\n ELSE 0 END AS infection\n from diagnoses_icd\n),\n-- ICD-9 codes for organ dysfunction - as sourced from Appendix 2 of above paper\norgan_diag_group as\n(\n SELECT subject_id, hadm_id,\n CASE\n -- Acute Organ Dysfunction Diagnosis Codes\n WHEN SUBSTR(icd9_code,1,3) IN ('458','293','570','584') THEN 1\n WHEN SUBSTR(icd9_code,1,4) IN ('7855','3483','3481',\n '2874','2875','2869','2866','5734') THEN 1\n ELSE 0 END AS organ_dysfunction,\n -- sepsis_explicit diagnosis of severe sepsis or septic shock\n CASE\n WHEN SUBSTR(icd9_code,1,5) IN ('99592','78552') THEN 1\n ELSE 0 END AS sepsis_explicit_sepsis\n from diagnoses_icd\n),\n
-- Mechanical ventilation\norgan_proc_group as\n(\n SELECT subject_id, hadm_id,\n CASE\n WHEN icd9_code IN ('9670', '9671', '9672') THEN 1\n ELSE 0 END AS mech_vent\n FROM procedures_icd\n),\n-- Aggregate above views together\naggregate as\n(\n SELECT subject_id, hadm_id,\n CASE\n WHEN hadm_id in\n (SELECT DISTINCT hadm_id\n FROM infection_group\n WHERE infection = 1)\n THEN 1\n ELSE 0 END AS infection,\n CASE\n WHEN hadm_id in\n (SELECT DISTINCT hadm_id\n FROM organ_diag_group\n WHERE sepsis_explicit_sepsis = 1)\n THEN 1\n ELSE 0 END AS sepsis_explicit_sepsis,\n CASE\n WHEN hadm_id in\n (SELECT DISTINCT hadm_id\n FROM organ_diag_group\n WHERE organ_dysfunction = 1)\n THEN 1\n ELSE 0 END AS organ_dysfunction,\n CASE\n WHEN hadm_id in\n (SELECT DISTINCT hadm_id\n FROM organ_proc_group\n WHERE mech_vent = 1)\n THEN 1\n ELSE 0 END AS mech_vent\n FROM admissions\n)\n-- Output component flags (explicit sepsis, organ dysfunction) and final flag (angus)\nSELECT subject_id, hadm_id, infection,\n sepsis_explicit_sepsis, organ_dysfunction, mech_vent,\nCASE\n WHEN sepsis_explicit_sepsis = 1 THEN 1\n WHEN infection = 1 AND organ_dysfunction = 1 THEN 1\n WHEN infection = 1 AND mech_vent = 1 THEN 1\n ELSE 0 END\nAS sepsis_angus\nFROM aggregate;\n-- jing add tail\nalter table mimic3.sepsis_angus\nowner to postgres;"
explicit <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS sepsis_explicit;\ncreate materialized view mimic3.sepsis_explicit\ntablespace pg_default\nas\n-- jing add head\n-- This code extracts sepsis_explicit sepsis using ICD-9 diagnosis codes\n-- That is, the two codes 995.92 (severe sepsis) or 785.52 (septic shock)\n-- These codes are extremely specific to sepsis, but have very low sensitivity\n-- From Iwashyna et al. (vs. chart reviews): 100% PPV, 9.3% sens, 100% specificity\n\nWITH co_dx AS\n(\n SELECT hadm_id\n -- sepsis codes\n , MAX(\n CASE\n WHEN icd9_code = '99592' THEN 1\n ELSE 0 END\n ) AS severe_sepsis\n , MAX(\n CASE\n WHEN icd9_code = '78552' THEN 1\n ELSE 0 END\n ) AS septic_shock\n from diagnoses_icd\n GROUP BY hadm_id\n)\nselect\n adm.subject_id\n , adm.hadm_id\n , co_dx.severe_sepsis\n , co_dx.septic_shock\n , case when co_dx.severe_sepsis = 1 or co_dx.septic_shock = 1\n then 1\n else 0 end as sepsis\nFROM admissions adm\nleft join co_dx\n on adm.hadm_id = co_dx.hadm_id\norder by adm.subject_id, adm.hadm_id;\n-- jing add tail\nalter table mimic3.sepsis_explicit\nowner to postgres;"
martin <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS sepsis_martin;\ncreate materialized view mimic3.sepsis_martin\nTABLESPACE pg_default\nAS\n WITH co_dx AS (\n SELECT diagnoses_icd.subject_id,\n diagnoses_icd.hadm_id,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 3) = '038'::text THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = ANY (ARRAY['0202'::text, '7907'::text, '1179'::text, '1125'::text]) THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 5) = '11281'::text THEN 1\n ELSE 0\n END) AS sepsis,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = '7991'::text THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 5) = ANY (ARRAY['51881'::text, '51882'::text, '51885'::text, '78609'::text]) THEN 1\n ELSE 0\n END) AS respiratory,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = ANY (ARRAY['4580'::text, '7855'::text, '4580'::text, '4588'::text, '4589'::text, '7963'::text]) THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 5) = ANY (ARRAY['785.51'::text, '785.59'::text]) THEN 1\n ELSE 0\n END) AS cardiovascular,\n max(\n
CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 3) = ANY (ARRAY['584'::text, '580'::text, '585'::text]) THEN 1\n ELSE 0\n END) AS renal,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 3) = '570'::text THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = ANY (ARRAY['5722'::text, '5733'::text]) THEN 1\n ELSE 0\n END) AS hepatic,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = ANY (ARRAY['2862'::text, '2866'::text, '2869'::text, '2873'::text, '2874'::text, '2875'::text]) THEN 1\n ELSE 0\n END) AS hematologic,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = '2762'::text THEN 1\n ELSE 0\n END) AS metabolic,\n max(\n CASE\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 3) = '293'::text THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 4) = ANY (ARRAY['3481'::text, '3483'::text]) THEN 1\n WHEN substr(diagnoses_icd.icd9_code::text, 1, 5) = ANY (ARRAY['78001'::text, '78009'::text]) THEN 1\n ELSE 0\n END) AS neurologic\n FROM mimic3.diagnoses_icd\n GROUP BY diagnoses_icd.subject_id, diagnoses_icd.hadm_id\n ), co_proc AS (\n SELECT procedures_icd.subject_id,\n procedures_icd.hadm_id,\n max(\n CASE\n WHEN procedures_icd.icd9_code::text = '967'::text THEN 1\n ELSE 0\n END) AS respiratory,\n max(\n CASE\n WHEN procedures_icd.icd9_code::text = '3995'::text THEN 1\n ELSE 0\n END) AS renal,\n max(\n CASE\n WHEN procedures_icd.icd9_code::text = '8914'::text THEN 1\n ELSE 0\n END) AS neurologic\n FROM mimic3.procedures_icd\n GROUP BY procedures_icd.subject_id, procedures_icd.hadm_id\n )\n SELECT adm.subject_id,\n adm.hadm_id,\n co_dx.sepsis,\n CASE\n WHEN co_dx.respiratory = 1 OR co_proc.respiratory = 1 OR co_dx.cardiovascular = 1 OR co_dx.renal = 1 OR co_proc.renal = 1 OR co_dx.hepatic = 1 OR co_dx.hematologic = 1 OR co_dx.metabolic = 1 OR co_dx.neurologic = 1 OR co_proc.neurologic = 1 THEN 1\n ELSE 0\n END AS organ_failure,\n CASE\n WHEN co_dx.respiratory = 1 OR co_proc.respiratory = 1 THEN 1\n ELSE 0\n END AS respiratory,\n co_dx.cardiovascular,\n CASE\n WHEN co_dx.renal = 1 OR co_proc.renal = 1 THEN 1\n ELSE 0\n END AS renal,\n co_dx.hepatic,\n co_dx.hematologic,\n co_dx.metabolic,\n CASE\n WHEN co_dx.neurologic = 1 OR co_proc.neurologic = 1 THEN 1\n ELSE 0\n END AS neurologic\n FROM mimic3.admissions adm\n LEFT JOIN co_dx ON adm.hadm_id = co_dx.hadm_id\n LEFT JOIN co_proc ON adm.hadm_id = co_proc.hadm_id\nWITH DATA;\n\nALTER TABLE mimic3.sepsis_martin\n OWNER TO postgres;"
# 2 diagnosis----------
if (do::right(ccs_multi_dx,2) =='gz'){
ccs_diagnosis_table_psql=paste0("SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS diagnosis_ccs_dx;\nDROP MATERIALIZED VIEW IF EXISTS diagnosis_ccs_diagnosis_table_sql;\nDROP TABLE IF EXISTS zzz;\nCREATE TABLE zzz\n(\n icd9_code CHAR(5) NOT NULL,\n ccs_matched_id VARCHAR(10),\n ccs_matched_name VARCHAR(100),\n ccs_id INTEGER,\n ccs_name VARCHAR(100),\n ccs_level1 VARCHAR(10),\n ccs_group1 VARCHAR(100),\n ccs_level2 VARCHAR(10),\n ccs_group2 VARCHAR(100),\n ccs_level3 VARCHAR(10),\n ccs_group3 VARCHAR(100),\n ccs_level4 VARCHAR(10),\n ccs_group4 VARCHAR(100)\n);\nCOPY zzz (icd9_code, ccs_level1, ccs_group1, ccs_level2, ccs_group2, ccs_level3, ccs_group3, ccs_level4, ccs_group4) FROM PROGRAM 'gzip -dc ",
ccs_multi_dx,
"' CSV HEADER;\nUPDATE zzz\nSET ccs_matched_id=tt.ccs_matched_id, ccs_matched_name=tt.ccs_matched_name,\n ccs_name=tt.ccs_name, ccs_id=CAST(tt.ccs_id AS INTEGER)\nFROM (\n SELECT icd9_code\n , COALESCE(ccs_level4, ccs_level3, ccs_level2, ccs_level1) AS ccs_matched_id\n , REGEXP_REPLACE(COALESCE(ccs_group4, ccs_group3, ccs_group2, ccs_group1), '\\[[0-9]+\\.\\]$', '') as ccs_matched_name\n , CASE\n WHEN ccs_group4 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group4, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group3 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group3, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group2 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group2, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group1 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group1, '\\[[0-9]+\\.\\]$', '')\n ELSE NULL END AS ccs_name\n , COALESCE(\n SUBSTRING(ccs_group4, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group3, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group2, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group1, '\\[([0-9]+)\\.\\]$')\n ) as ccs_id\n FROM zzz\n) AS tt\nWHERE zzz.icd9_code = tt.icd9_code;\nalter table mimic3.zzz\nowner to postgres;")
}else if (do::right(ccs_multi_dx,2) =='sv'){
ccs_diagnosis_table_psql=paste0("SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS diagnosis_ccs_dx;\nDROP MATERIALIZED VIEW IF EXISTS diagnosis_ccs_diagnosis_table_sql;\nDROP TABLE IF EXISTS zzz;\nCREATE TABLE zzz\n(\n icd9_code CHAR(5) NOT NULL,\n ccs_matched_id VARCHAR(10),\n ccs_matched_name VARCHAR(100),\n ccs_id INTEGER,\n ccs_name VARCHAR(100),\n ccs_level1 VARCHAR(10),\n ccs_group1 VARCHAR(100),\n ccs_level2 VARCHAR(10),\n ccs_group2 VARCHAR(100),\n ccs_level3 VARCHAR(10),\n ccs_group3 VARCHAR(100),\n ccs_level4 VARCHAR(10),\n ccs_group4 VARCHAR(100)\n);\nCOPY zzz (icd9_code, ccs_level1, ccs_group1, ccs_level2, ccs_group2, ccs_level3, ccs_group3, ccs_level4, ccs_group4) FROM ' ",
ccs_multi_dx,
"' CSV HEADER;\nUPDATE zzz\nSET ccs_matched_id=tt.ccs_matched_id, ccs_matched_name=tt.ccs_matched_name,\n ccs_name=tt.ccs_name, ccs_id=CAST(tt.ccs_id AS INTEGER)\nFROM (\n SELECT icd9_code\n , COALESCE(ccs_level4, ccs_level3, ccs_level2, ccs_level1) AS ccs_matched_id\n , REGEXP_REPLACE(COALESCE(ccs_group4, ccs_group3, ccs_group2, ccs_group1), '\\[[0-9]+\\.\\]$', '') as ccs_matched_name\n , CASE\n WHEN ccs_group4 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group4, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group3 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group3, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group2 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group2, '\\[[0-9]+\\.\\]$', '')\n WHEN ccs_group1 ~ '\\[([0-9]+)\\.\\]$' THEN REGEXP_REPLACE(ccs_group1, '\\[[0-9]+\\.\\]$', '')\n ELSE NULL END AS ccs_name\n , COALESCE(\n SUBSTRING(ccs_group4, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group3, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group2, '\\[([0-9]+)\\.\\]$'),\n SUBSTRING(ccs_group1, '\\[([0-9]+)\\.\\]$')\n ) as ccs_id\n FROM zzz\n) AS tt\nWHERE zzz.icd9_code = tt.icd9_code;\nalter table mimic3.zzz\nowner to postgres;")
}else{
stop('ccs_multi_dx must be csv or csv.gz file path with filename')
}
ccs_dx <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS diagnosis_ccs_dx;\ncreate materialized view mimic3.diagnosis_ccs_dx\ntablespace pg_default\nas\n-- jing add head\n-- add in matched ID, name, and ccs_id\n-- matched id (ccs_mid): the ccs ID with the hierachy, e.g. 7.1.2.1\n-- name (ccs_name): the most granular CCS category the diagnosis is in\n-- ID (ccs_id): the CCS identifier for the ICD-9 code (integer)\nSELECT\n icd9_code\n , COALESCE(ccs_level4, ccs_level3, ccs_level2, ccs_level1) AS ccs_matched_id\n -- remove the trailing ccs_id from name column, i.e. \"Burns [240.]\" -> \"Burns\"\n , REGEXP_REPLACE(COALESCE(ccs_group4, ccs_group3, ccs_group2, ccs_group1), '\\[[0-9]+\\.\\]$', '') as ccs_matched_name\n -- ccs_id is sometimes present at a higher level of granularity\n -- e.g. for 7.1.2.1, the CCS name is at level 7.1.2\n -- therefore we pull from the first category to have the CCS ID\n , CASE\n WHEN REGEXP_CONTAINS(ccs_group4, '\\[([0-9]+)\\.\\]$') THEN REGEXP_REPLACE(ccs_group4, '\\[[0-9]+\\.\\]$', '')\n WHEN REGEXP_CONTAINS(ccs_group3, '\\[([0-9]+)\\.\\]$') THEN REGEXP_REPLACE(ccs_group3, '\\[[0-9]+\\.\\]$', '')\n WHEN REGEXP_CONTAINS(ccs_group2, '\\[([0-9]+)\\.\\]$') THEN REGEXP_REPLACE(ccs_group2, '\\[[0-9]+\\.\\]$', '')\n WHEN REGEXP_CONTAINS(ccs_group1, '\\[([0-9]+)\\.\\]$') THEN REGEXP_REPLACE(ccs_group1, '\\[[0-9]+\\.\\]$', '')\n ELSE NULL END AS ccs_name\n -- extract the trailing ccs_id from name, i.e. \"Burns [240.]\" -> \"240\"\n , COALESCE(\n REGEXP_EXTRACT(ccs_group4, '\\[([0-9]+)\\.\\]$'),\n REGEXP_EXTRACT(ccs_group3, '\\[([0-9]+)\\.\\]$'),\n REGEXP_EXTRACT(ccs_group2, '\\[([0-9]+)\\.\\]$'),\n REGEXP_EXTRACT(ccs_group1, '\\[([0-9]+)\\.\\]$')\n ) as ccs_id\n , ccs_level1\n , ccs_group1\n , ccs_level2\n , ccs_group2\n , ccs_level3\n , ccs_group3\n , ccs_level4\n , ccs_group4\nFROM diagnosis_ccs_diagnosis_table_sql\nORDER BY icd9_code;\n-- jing add tail\nalter table mimic3.diagnosis_ccs_dx\nowner to postgres;"
# 6 organfailure-------------
kdigo_creatinine <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_kdigo_creatinine;\ncreate materialized view mimic3.organfailure_kdigo_creatinine\ntablespace pg_default\nas\n-- jing add head\n-- Extract all creatinine values FROM labevents around patient's ICU stay\nwith cr as\n(\nselect\n ie.icustay_id\n , ie.intime, ie.outtime\n , le.valuenum as creat\n , le.charttime\n FROM icustays ie\n left join labevents le\n on ie.subject_id = le.subject_id\n and le.ITEMID = 50912\n and le.VALUENUM is not null\n and datetime_diff(le.charttime, ie.intime,'HOUR') <= (7*24-6)\n and le.CHARTTIME >= DATETIME_SUB(ie.intime, INTERVAL '6' HOUR)\n and le.CHARTTIME <= DATETIME_ADD(ie.intime, INTERVAL '7' DAY)\n)\n-- add in the lowest value in the previous 48 hours/7 days\nSELECT\n cr.icustay_id\n , cr.charttime\n , cr.creat\n , MIN(cr48.creat) AS creat_low_past_48hr\n , MIN(cr7.creat) AS creat_low_past_7day\nFROM cr\n-- add in all creatinine values in the last 48 hours\nLEFT JOIN cr cr48\n ON cr.icustay_id = cr48.icustay_id\n AND cr48.charttime < cr.charttime\n AND datetime_diff(cr.charttime, cr48.charttime,'HOUR') <= 48\n-- add in all creatinine values in the last 7 days\nLEFT JOIN cr cr7\n ON cr.icustay_id = cr7.icustay_id\n AND cr7.charttime < cr.charttime\n AND datetime_diff(cr.charttime, cr7.charttime,'DAY') <= 7\nGROUP BY cr.icustay_id, cr.charttime, cr.creat\nORDER BY cr.icustay_id, cr.charttime, cr.creat;\n-- jing add tail\nalter table mimic3.organfailure_kdigo_creatinine\nowner to postgres;"
kdigo_uo <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_kdigo_uo;\ncreate materialized view mimic3.organfailure_kdigo_uo\ntablespace pg_default\nas\n-- jing add head\nwith ur_stg as\n(\n select io.icustay_id, io.charttime\n -- we have joined each row to all rows preceding within 24 hours\n -- we can now sum these rows to get total uo over the last 24 hours\n -- we can use case statements to restrict it to only the last 6/12 hours\n -- therefore we have three sums:\n -- 1) over a 6 hour period\n -- 2) over a 12 hour period\n -- 3) over a 24 hour period\n\n -- note that we assume data charted at charttime corresponds to 1 hour of uo\n -- therefore we use '5' and '11' to restrict the period, rather than 6/12\n -- this assumption may overestimate uo rate when documentation is done less than hourly\n , sum(case when datetime_diff(io.charttime, iosum.charttime,'HOUR') <= 5\n then iosum.VALUE\n else null end) as urineoutput_6hr\n , sum(case when datetime_diff(io.charttime, iosum.charttime,'HOUR') <= 11\n then iosum.VALUE\n else null end) as urineoutput_12hr\n -- 24 hours\n , sum(iosum.VALUE) as urineoutput_24hr\n\n -- retain the earliest time used for each summation\n -- this is later used to tabulate rates\n , MIN(case when io.charttime <= DATETIME_ADD(iosum.charttime, INTERVAL '5' HOUR)\n then iosum.charttime\n else null end)\n AS starttime_6hr\n , MIN(case when io.charttime <= DATETIME_ADD(iosum.charttime, INTERVAL '11' HOUR)\n then iosum.charttime\n else null end)\n AS starttime_12hr\n , MIN(iosum.charttime) AS starttime_24hr\n from fluid_balance_urine_output io\n -- this join gives you all uo measurements over a 24 hour period\n left join fluid_balance_urine_output iosum\n on io.icustay_id = iosum.icustay_id\n and io.charttime >= iosum.charttime\n and io.charttime <= (DATETIME_ADD(iosum.charttime, INTERVAL '23' HOUR))\n group by io.icustay_id, io.charttime\n)\n-- calculate hours used to sum uo over\n, ur_stg2 AS\n(\n select\n icustay_id\n , charttime\n , urineoutput_6hr\n , urineoutput_12hr\n , urineoutput_24hr\n
-- calculate time over which we summed uo\n -- note: adding 1 hour as we assume data charted corresponds to previous hour\n -- i.e. if documentation is:\n -- 10:00, 100 mL\n -- 11:00, 50 mL\n -- then this is two hours of documentation, even though (11:00 - 10:00) is 1 hour\n , ROUND(datetime_diff(charttime, starttime_6hr, 'HOUR'),4) + 1 AS uo_tm_6hr\n , ROUND(datetime_diff(charttime, starttime_12hr, 'HOUR'),4) + 1 AS uo_tm_12hr\n , ROUND(datetime_diff(charttime, starttime_24hr, 'HOUR'),4) + 1 AS uo_tm_24hr\n from ur_stg\n)\nselect\n ur.icustay_id\n, ur.charttime\n, wd.weight\n, ur.urineoutput_6hr\n, ur.urineoutput_12hr\n, ur.urineoutput_24hr\n, ROUND(CAST((ur.urineoutput_6hr/wd.weight/uo_tm_6hr) AS NUMERIC), 4) AS uo_rt_6hr\n, ROUND(CAST((ur.urineoutput_12hr/wd.weight/uo_tm_12hr) AS NUMERIC), 4) AS uo_rt_12hr\n, ROUND(CAST((ur.urineoutput_24hr/wd.weight/uo_tm_24hr) AS NUMERIC), 4) AS uo_rt_24hr\n-- time of earliest uo measurement that was used to calculate the rate\n, uo_tm_6hr\n, uo_tm_12hr\n, uo_tm_24hr\nfrom ur_stg2 ur\nleft join durations_weight_durations wd\n on ur.icustay_id = wd.icustay_id\n and ur.charttime >= wd.starttime\n and ur.charttime < wd.endtime\norder by icustay_id, charttime;\n-- jing add tail\nalter table mimic3.organfailure_kdigo_uo\nowner to postgres;"
kdigo_stages <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_kdigo_stages;\ncreate materialized view mimic3.organfailure_kdigo_stages\ntablespace pg_default\nas\n-- jing add head\n-- This query checks if the patient had AKI according to KDIGO.\n-- AKI is calculated every time a creatinine or urine output measurement occurs.\n-- Baseline creatinine is defined as the lowest creatinine in the past 7 days.\n\n-- get creatinine stages\nwith cr_stg AS\n(\n SELECT\n cr.icustay_id\n , cr.charttime\n , cr.creat\n , case\n -- 3x baseline\n when cr.creat >= (cr.creat_low_past_7day*3.0) then 3\n -- *OR* cr >= 4.0 with associated increase\n when cr.creat >= 4\n -- For patients reaching Stage 3 by SCr >4.0 mg/dl\n -- require that the patient first achieve ... acute increase >= 0.3 within 48 hr\n -- *or* an increase of >= 1.5 times baseline\n and (cr.creat_low_past_48hr <= 3.7 OR cr.creat >= (1.5*cr.creat_low_past_7day))\n then 3 \n -- TODO: initiation of rrt\n when cr.creat >= (cr.creat_low_past_7day*2.0) then 2\n when cr.creat >= (cr.creat_low_past_48hr+0.3) then 1\n when cr.creat >= (cr.creat_low_past_7day*1.5) then 1\n else 0 end as aki_stage_creat\n FROM organfailure_kdigo_creatinine cr\n)\n-- stages for uo / creat\n, uo_stg as\n(\n select\n uo.icustay_id\n , uo.charttime\n , uo.weight\n , uo.uo_rt_6hr\n , uo.uo_rt_12hr\n , uo.uo_rt_24hr\n -- AKI stages according to urine output\n , CASE\n WHEN uo.uo_rt_6hr IS NULL THEN NULL\n -- require patient to be in ICU for at least 6 hours to stage uo\n WHEN uo.charttime <= DATETIME_ADD(ie.intime, INTERVAL '6' HOUR) THEN 0\n
-- require the uo rate to be calculated over half the period\n -- i.e. for uo rate over 24 hours, require documentation at least 12 hr apart\n WHEN uo.uo_tm_24hr >= 11 AND uo.uo_rt_24hr < 0.3 THEN 3\n WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr = 0 THEN 3\n WHEN uo.uo_tm_12hr >= 5 AND uo.uo_rt_12hr < 0.5 THEN 2\n WHEN uo.uo_tm_6hr >= 2 AND uo.uo_rt_6hr < 0.5 THEN 1\n ELSE 0 END AS aki_stage_uo\n from organfailure_kdigo_uo uo\n INNER JOIN icustays ie\n ON uo.icustay_id = ie.icustay_id\n)\n-- get all charttimes documented\n, tm_stg AS\n(\n SELECT\n icustay_id, charttime\n FROM cr_stg\n UNION DISTINCT\n SELECT\n icustay_id, charttime\n FROM uo_stg\n)\nselect\n ie.icustay_id\n , tm.charttime\n , cr.creat\n , cr.aki_stage_creat\n , uo.uo_rt_6hr\n , uo.uo_rt_12hr\n , uo.uo_rt_24hr\n , uo.aki_stage_uo\n -- Classify AKI using both creatinine/urine output criteria\n , GREATEST(\n COALESCE(cr.aki_stage_creat, 0),\n COALESCE(uo.aki_stage_uo, 0)\n ) AS aki_stage\nFROM icustays ie\n-- get all possible charttimes as listed in tm_stg\nLEFT JOIN tm_stg tm\n ON ie.icustay_id = tm.icustay_id\nLEFT JOIN cr_stg cr\n ON ie.icustay_id = cr.icustay_id\n AND tm.charttime = cr.charttime\nLEFT JOIN uo_stg uo\n ON ie.icustay_id = uo.icustay_id\n AND tm.charttime = uo.charttime\norder by ie.icustay_id, tm.charttime;\n-- jing add tail\nalter table mimic3.organfailure_kdigo_stages\nowner to postgres;"
kdigo_stages_48hr <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_kdigo_stages_48hr;\ncreate materialized view mimic3.organfailure_kdigo_stages_48hr\ntablespace pg_default\nas\n-- jing add head\n-- This query checks if the patient had AKI during the first 48 hours of their ICU\n-- stay according to the KDIGO guideline.\n-- https://kdigo.org/wp-content/uploads/2016/10/KDIGO-2012-AKI-Guideline-English.pdf\n\n-- get the worst staging of creatinine in the first 48 hours\nWITH cr_aki AS\n(\n SELECT\n k.icustay_id\n , k.charttime\n , k.creat\n , k.aki_stage_creat\n , ROW_NUMBER() OVER (PARTITION BY k.icustay_id ORDER BY k.aki_stage_creat DESC, k.creat DESC) AS rn\n FROM icustays ie\n INNER JOIN organfailure_kdigo_stages k\n ON ie.icustay_id = k.icustay_id\n WHERE datetime_diff(k.charttime, ie.intime,'HOUR') > -6\n AND datetime_diff(k.charttime, ie.intime,'HOUR') <= 48\n AND k.aki_stage_creat IS NOT NULL\n)\n-- get the worst staging of urine output in the first 48 hours\n, uo_aki AS\n(\n SELECT\n k.icustay_id\n , k.charttime\n , k.uo_rt_6hr, k.uo_rt_12hr, k.uo_rt_24hr\n , k.aki_stage_uo\n , ROW_NUMBER() OVER \n (\n PARTITION BY k.icustay_id\n ORDER BY k.aki_stage_uo DESC, k.uo_rt_24hr DESC, k.uo_rt_12hr DESC, k.uo_rt_6hr DESC\n ) AS rn\n FROM icustays ie\n INNER JOIN organfailure_kdigo_stages k\n ON ie.icustay_id = k.icustay_id\n WHERE datetime_diff(k.charttime, ie.intime,'HOUR') > -6\n AND datetime_diff(k.charttime, ie.intime,'HOUR') <= 48\n AND k.aki_stage_uo IS NOT NULL\n)\n-- final table is aki_stage, include worst cr/uo for convenience\nselect\n ie.icustay_id\n , cr.charttime as charttime_creat\n , cr.creat\n , cr.aki_stage_creat\n , uo.charttime as charttime_uo\n , uo.uo_rt_6hr\n , uo.uo_rt_12hr\n , uo.uo_rt_24hr\n , uo.aki_stage_uo\n\n -- Classify AKI using both creatinine/urine output criteria\n , GREATEST(\n COALESCE(cr.aki_stage_creat, 0),\n COALESCE(uo.aki_stage_uo, 0)\n ) AS aki_stage_48hr\n , CASE WHEN cr.aki_stage_creat > 0 OR uo.aki_stage_uo > 0 THEN 1 ELSE 0 END AS aki_48hr\n\nFROM icustays ie\nLEFT JOIN cr_aki cr\n ON ie.icustay_id = cr.icustay_id\n AND cr.rn = 1\nLEFT JOIN uo_aki uo\n ON ie.icustay_id = uo.icustay_id\n AND uo.rn = 1\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.organfailure_kdigo_stages_48hr\nowner to postgres;"
kdigo_stages_7day <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_kdigo_stages_7day;\ncreate materialized view mimic3.organfailure_kdigo_stages_7day\ntablespace pg_default\nas\n-- jing add head\n-- This query checks if the patient had AKI during the first 7 days of their ICU\n-- stay according to the KDIGO guideline.\n-- https://kdigo.org/wp-content/uploads/2016/10/KDIGO-2012-AKI-Guideline-English.pdf\n\n-- get the worst staging of creatinine in the first 48 hours\nWITH cr_aki AS\n(\n SELECT\n k.icustay_id\n , k.charttime\n , k.creat\n , k.aki_stage_creat\n , ROW_NUMBER() OVER (PARTITION BY k.icustay_id ORDER BY k.aki_stage_creat DESC, k.creat DESC) AS rn\n FROM icustays ie\n INNER JOIN organfailure_kdigo_stages k\n ON ie.icustay_id = k.icustay_id\n WHERE datetime_diff(k.charttime, ie.intime,'HOUR') > -6\n AND datetime_diff(k.charttime, ie.intime,'DAY') <= 7\n AND k.aki_stage_creat IS NOT NULL\n)\n-- get the worst staging of urine output in the first 48 hours\n, uo_aki AS\n(\n SELECT\n k.icustay_id\n , k.charttime\n , k.uo_rt_6hr, k.uo_rt_12hr, k.uo_rt_24hr\n , k.aki_stage_uo\n , ROW_NUMBER() OVER \n (\n PARTITION BY k.icustay_id\n ORDER BY k.aki_stage_uo DESC, k.uo_rt_24hr DESC, k.uo_rt_12hr DESC, k.uo_rt_6hr DESC\n ) AS rn\n FROM icustays ie\n INNER JOIN organfailure_kdigo_stages k\n ON ie.icustay_id = k.icustay_id\n WHERE datetime_diff(k.charttime, ie.intime,'HOUR') > -6\n AND datetime_diff(k.charttime, ie.intime,'DAY') <= 7\n AND k.aki_stage_uo IS NOT NULL\n)\n-- final table is aki_stage, include worst cr/uo for convenience\nselect\n ie.icustay_id\n , cr.charttime as charttime_creat\n , cr.creat\n , cr.aki_stage_creat\n , uo.charttime as charttime_uo\n , uo.uo_rt_6hr\n , uo.uo_rt_12hr\n , uo.uo_rt_24hr\n , uo.aki_stage_uo\n\n -- Classify AKI using both creatinine/urine output criteria\n , GREATEST(\n COALESCE(cr.aki_stage_creat, 0),\n COALESCE(uo.aki_stage_uo, 0)\n ) AS aki_stage_7day\n , CASE WHEN cr.aki_stage_creat > 0 OR uo.aki_stage_uo > 0 THEN 1 ELSE 0 END AS aki_7day\n\nFROM icustays ie\nLEFT JOIN cr_aki cr\n ON ie.icustay_id = cr.icustay_id\n AND cr.rn = 1\nLEFT JOIN uo_aki uo\n ON ie.icustay_id = uo.icustay_id\n AND uo.rn = 1\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.organfailure_kdigo_stages_7day\nowner to postgres;"
meld <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS organfailure_meld;\ncreate materialized view mimic3.organfailure_meld\nTABLESPACE pg_default\nAS\n WITH cohort AS (\n SELECT ie.subject_id,\n ie.hadm_id,\n ie.icustay_id,\n ie.intime,\n ie.outtime,\n labs.creatinine_max,\n labs.bilirubin_max,\n labs.inr_max,\n labs.sodium_min,\n r.rrt\n FROM mimic3.icustays ie\n JOIN mimic3.admissions adm ON ie.hadm_id = adm.hadm_id\n JOIN mimic3.patients pat ON ie.subject_id = pat.subject_id\n LEFT JOIN mimic3.firstday_labs labs ON ie.icustay_id = labs.icustay_id\n LEFT JOIN mimic3.firstday_rrt r ON ie.icustay_id = r.icustay_id\n ), score AS (\n SELECT cohort.subject_id,\n cohort.hadm_id,\n cohort.icustay_id,\n cohort.rrt,\n cohort.creatinine_max,\n cohort.bilirubin_max,\n cohort.inr_max,\n cohort.sodium_min,\n CASE\n WHEN cohort.sodium_min IS NULL THEN 0.0::double precision\n WHEN cohort.sodium_min > 137::double precision THEN 0.0::double precision\n WHEN cohort.sodium_min < 125::double precision THEN 12.0::double precision\n ELSE 137.0::double precision - cohort.sodium_min\n END AS sodium_score,\n CASE\n WHEN cohort.rrt = 1 OR cohort.creatinine_max > 4.0::double precision THEN 0.957::double precision * ln(4::double precision)\n WHEN cohort.creatinine_max < 1::double precision THEN 0.957::double precision * ln(1::double precision)\n ELSE 0.957::double precision * COALESCE(ln(cohort.creatinine_max), ln(1::double precision))\n END AS creatinine_score,\n
CASE\n WHEN cohort.bilirubin_max < 1::double precision THEN 0.378::double precision * ln(1::double precision)\n ELSE 0.378::double precision * COALESCE(ln(cohort.bilirubin_max), ln(1::double precision))\n END AS bilirubin_score,\n CASE\n WHEN cohort.inr_max < 1::double precision THEN 1.120::double precision * ln(1::double precision) + 0.643::double precision\n ELSE 1.120::double precision * COALESCE(ln(cohort.inr_max), ln(1::double precision)) + 0.643::double precision\n END AS inr_score\n FROM cohort\n ), score2 AS (\n SELECT score.subject_id,\n score.hadm_id,\n score.icustay_id,\n score.rrt,\n score.creatinine_max,\n score.bilirubin_max,\n score.inr_max,\n score.sodium_min,\n score.creatinine_score,\n score.sodium_score,\n score.bilirubin_score,\n score.inr_score,\n CASE\n WHEN (score.creatinine_score + score.bilirubin_score + score.inr_score) > 40::double precision THEN 40.0\n ELSE round((score.creatinine_score + score.bilirubin_score + score.inr_score)::numeric, 1) * 10::numeric\n END AS meld_initial\n FROM score\n )\n SELECT score2.subject_id,\n score2.hadm_id,\n score2.icustay_id,\n score2.meld_initial,\n CASE\n WHEN score2.meld_initial > 11::numeric THEN score2.meld_initial::double precision + 1.32::double precision * score2.sodium_score - (0.033 * score2.meld_initial)::double precision * score2.sodium_score\n ELSE score2.meld_initial::double precision\n END AS meld,\n score2.rrt,\n score2.creatinine_max,\n score2.bilirubin_max,\n score2.inr_max,\n score2.sodium_min\n FROM score2\n ORDER BY score2.icustay_id\nWITH DATA;\n\nALTER TABLE mimic3.organfailure_meld\n OWNER TO postgres;"
# 9 severityscores-------------
apsiii <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_apsiii;\ncreate materialized view mimic3.severityscores_apsiii\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Acute Physiology Score III (APS III)\n-- This query extracts the acute physiology score III.\n-- This score is a measure of patient severity of illness.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for APS III:\n-- Knaus WA, Wagner DP, Draper EA, Zimmerman JE, Bergner M, Bastos PG, Sirio CA, Murphy DJ, Lotring T, Damiano A.\n-- The APACHE III prognostic system. Risk prediction of hospital mortality for critically ill hospitalized adults.\n-- Chest Journal. 1991 Dec 1;100(6):1619-36.\n\n-- Reference for the equation for calibrating APS III to hospital mortality:\n-- Johnson, A. E. W. (2015). mortality prediction and acuity assessment in critical care.\n-- University of Oxford, Oxford, UK.\n\n-- Variables used in APS III:\n-- gcs\n-- VITALS: Heart rate, mean blood pressure, temperature, respiration rate\n-- FLAGS: ventilation/cpap, chronic dialysis\n-- IO: urine output\n-- LABS: pao2, A-aDO2, hematocrit, wbc, creatinine\n-- , blood urea nitrogen, sodium, albumin, bilirubin, glucose, pH, pCO2\n\n-- The following views are required to run this query:\n-- 1) firstday_urine_output - generated by urine-output-first-day.sql\n-- 2) firstday_ventilation - generated by ventilated-first-day.sql\n-- 3) firstday_vitals - generated by vitals-first-day.sql\n-- 4) firstday_gcs - generated by gcs-first-day.sql\n-- 5) firstday_labs - generated by labs-first-day.sql\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate icustay_ids.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n-- List of TODO:\n-- The site of temperature is not incorporated. Axillary measurements should be increased by 1 degree.\n
-- Unfortunately the data for metavision is not available at the moment.\n-- 674 | temp. Site\n-- 224642 | temperature Site\n\nwith pa as\n(\n select bg.icustay_id, bg.charttime\n , po2 as PaO2\n , ROW_NUMBER() over (partition by bg.icustay_id ORDER BY bg.po2 DESC) as rn\n from firstday_blood_gas_arterial bg\n left join durations_ventilation_durations vd\n on bg.icustay_id = vd.icustay_id\n and bg.charttime >= vd.starttime\n and bg.charttime <= vd.endtime\n WHERE vd.icustay_id is null -- patient is *not* ventilated\n -- and fio2 < 50, or if no fio2, assume room air\n AND coalesce(fio2, fio2_chartevents, 21) < 50\n AND bg.po2 IS NOT NULL\n)\n, aa as\n(\n -- join blood gas to ventilation durations to determine if patient was vent\n -- also join to cpap table for the same purpose\n select bg.icustay_id, bg.charttime\n , bg.aado2\n , ROW_NUMBER() over (partition by bg.icustay_id ORDER BY bg.aado2 DESC) as rn\n -- row number indicating the highest AaDO2\n from firstday_blood_gas_arterial bg\n INNER JOIN durations_ventilation_durations vd\n on bg.icustay_id = vd.icustay_id\n and bg.charttime >= vd.starttime\n and bg.charttime <= vd.endtime\n WHERE vd.icustay_id is not null -- patient is ventilated\n AND coalesce(fio2, fio2_chartevents) >= 50\n AND bg.aado2 IS NOT NULL\n)\n-- because ph/pco2 rules are an interaction *within* a blood gas, we calculate them here\n
-- the worse score is then taken for the final calculation\n, acidbase as\n(\n select bg.icustay_id\n , ph, pco2 as paco2\n , case\n when ph is null or pco2 is null then null\n when ph < 7.20 then\n case\n when pco2 < 50 then 12\n else 4\n end\n when ph < 7.30 then\n case\n when pco2 < 30 then 9\n when pco2 < 40 then 6\n when pco2 < 50 then 3\n else 2\n end\n when ph < 7.35 then\n case\n when pco2 < 30 then 9\n when pco2 < 45 then 0\n else 1\n end\n when ph < 7.45 then\n case\n when pco2 < 30 then 5\n when pco2 < 45 then 0\n else 1\n end\n when ph < 7.50 then\n case\n when pco2 < 30 then 5\n when pco2 < 35 then 0\n when pco2 < 45 then 2\n else 12\n end\n when ph < 7.60 then\n case\n when pco2 < 40 then 3\n else 12\n end\n else -- ph >= 7.60\n case\n when pco2 < 25 then 0\n when pco2 < 40 then 3\n else 12\n end\n end as acidbase_score\n from firstday_blood_gas_arterial bg\n where ph is not null and pco2 is not null\n)\n, acidbase_max as\n(\n select icustay_id, acidbase_score, ph, paco2\n -- create integer which indexes maximum value of score with 1\n , ROW_NUMBER() over (partition by icustay_id ORDER BY acidbase_score DESC) as acidbase_rn\n from acidbase\n)\n-- define acute renal failure (ARF) as:\n-- creatinine >=1.5 mg/dl\n-- and urine output <410 cc/day\n-- and no chronic dialysis\n, arf as\n(\n select ie.icustay_id\n , case\n when labs.creatinine_max >= 1.5\n and uo.urineoutput < 410\n -- acute renal failure is only coded if the patient is not on chronic dialysis\n
-- we use ICD-9 coding of ESRD as a proxy for chronic dialysis\n and icd.ckd = 0\n then 1\n else 0 end as arf\n FROM icustays ie\n left join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\n left join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n left join\n (\n select hadm_id\n , max(case\n -- severe kidney failure requiring use of dialysis\n when icd9_code in ('5854','5855','5856') then 1\n -- we do not include 5859 as that is sometimes coded for acute-on-chronic ARF\n else 0 end)\n as ckd\n from diagnoses_icd\n group by hadm_id\n ) icd\n on ie.hadm_id = icd.hadm_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n , ie.intime\n , ie.outtime\n\n , vital.heartrate_min\n , vital.heartrate_max\n , vital.meanbp_min\n , vital.meanbp_max\n , vital.tempc_min\n , vital.tempc_max\n , vital.resprate_min\n , vital.resprate_max\n\n , pa.pao2\n , aa.aado2\n\n , ab.ph\n , ab.paco2\n , ab.acidbase_score\n\n , labs.hematocrit_min\n , labs.hematocrit_max\n , labs.wbc_min\n , labs.wbc_max\n , labs.creatinine_min\n , labs.creatinine_max\n , labs.bun_min\n , labs.bun_max\n , labs.sodium_min\n , labs.sodium_max\n , labs.albumin_min\n , labs.albumin_max\n , labs.bilirubin_min\n , labs.bilirubin_max\n\n , case\n when labs.glucose_max is null and vital.glucose_max is null\n then null\n when labs.glucose_max is null or vital.glucose_max > labs.glucose_max\n then vital.glucose_max\n when vital.glucose_max is null or labs.glucose_max > vital.glucose_max\n then labs.glucose_max\n else labs.glucose_max -- if equal, just pick labs\n end as glucose_max\n\n , case\n when labs.glucose_min is null and vital.glucose_min is null\n then null\n when labs.glucose_min is null or vital.glucose_min < labs.glucose_min\n then vital.glucose_min\n when vital.glucose_min is null or labs.glucose_min < vital.glucose_min\n then labs.glucose_min\n else labs.glucose_min -- if equal, just pick labs\n end as glucose_min\n\n
-- , labs.bicarbonate_min\n -- , labs.bicarbonate_max\n , vent.vent\n , uo.urineoutput\n -- gcs and its components\n , gcs.mingcs\n , gcs.gcsmotor, gcs.gcsverbal, gcs.gcseyes, gcs.endotrachflag\n -- acute renal failure\n , arf.arf as arf\n\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\n\n-- join to above views - the row number filters to 1 row per icustay_id\nleft join pa\n on ie.icustay_id = pa.icustay_id\n and pa.rn = 1\nleft join aa\n on ie.icustay_id = aa.icustay_id\n and aa.rn = 1\nleft join acidbase_max ab\n on ie.icustay_id = ab.icustay_id\n and ab.acidbase_rn = 1\nleft join arf\n on ie.icustay_id = arf.icustay_id\n\n-- join to custom tables to get more data....\nleft join firstday_ventilation vent\n on ie.icustay_id = vent.icustay_id\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\nleft join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n)\n-- First, we calculate the score for the minimum values\n, score_min as\n(\n select cohort.subject_id, cohort.hadm_id, cohort.icustay_id\n , case\n when heartrate_min is null then null\n when heartrate_min < 40 then 8\n when heartrate_min < 50 then 5\n when heartrate_min < 100 then 0\n when heartrate_min < 110 then 1\n when heartrate_min < 120 then 5\n when heartrate_min < 140 then 7\n when heartrate_min < 155 then 13\n when heartrate_min >= 155 then 17\n end as hr_score\n\n , case\n when meanbp_min is null then null\n when meanbp_min < 40 then 23\n when meanbp_min < 60 then 15\n when meanbp_min < 70 then 7\n when meanbp_min < 80 then 6\n when meanbp_min < 100 then 0\n when meanbp_min < 120 then 4\n when meanbp_min < 130 then 7\n when meanbp_min < 140 then 9\n when meanbp_min >= 140 then 10\n end as meanbp_score\n\n
-- TODO: add 1 degree to axillary measurements\n , case\n when tempc_min is null then null\n when tempc_min < 33.0 then 20\n when tempc_min < 33.5 then 16\n when tempc_min < 34.0 then 13\n when tempc_min < 35.0 then 8\n when tempc_min < 36.0 then 2\n when tempc_min < 40.0 then 0\n when tempc_min >= 40.0 then 4\n end as temp_score\n\n , case\n when resprate_min is null then null\n -- special case for ventilated patients\n when vent = 1 and resprate_min < 14 then 0\n when resprate_min < 6 then 17\n when resprate_min < 12 then 8\n when resprate_min < 14 then 7\n when resprate_min < 25 then 0\n when resprate_min < 35 then 6\n when resprate_min < 40 then 9\n when resprate_min < 50 then 11\n when resprate_min >= 50 then 18\n end as resprate_score\n\n , case\n when hematocrit_min is null then null\n when hematocrit_min < 41.0 then 3\n when hematocrit_min < 50.0 then 0\n when hematocrit_min >= 50.0 then 3\n end as hematocrit_score\n\n , case\n when wbc_min is null then null\n when wbc_min < 1.0 then 19\n when wbc_min < 3.0 then 5\n when wbc_min < 20.0 then 0\n when wbc_min < 25.0 then 1\n when wbc_min >= 25.0 then 5\n end as wbc_score\n\n , case\n when creatinine_min is null then null\n when arf = 1 and creatinine_min < 1.5 then 0\n when arf = 1 and creatinine_min >= 1.5 then 10\n when creatinine_min < 0.5 then 3\n when creatinine_min < 1.5 then 0\n when creatinine_min < 1.95 then 4\n when creatinine_min >= 1.95 then 7\n end as creatinine_score\n\n , case\n when bun_min is null then null\n when bun_min < 17.0 then 0\n when bun_min < 20.0 then 2\n when bun_min < 40.0 then 7\n when bun_min < 80.0 then 11\n when bun_min >= 80.0 then 12\n end as bun_score\n\n , case\n when sodium_min is null then null\n when sodium_min < 120 then 3\n when sodium_min < 135 then 2\n when sodium_min < 155 then 0\n when sodium_min >= 155 then 4\n end as sodium_score\n\n , case\n when albumin_min is null then null\n when albumin_min < 2.0 then 11\n when albumin_min < 2.5 then 6\n when albumin_min < 4.5 then 0\n when albumin_min >= 4.5 then 4\n end as albumin_score\n\n , case\n when bilirubin_min is null then null\n when bilirubin_min < 2.0 then 0\n when bilirubin_min < 3.0 then 5\n when bilirubin_min < 5.0 then 6\n when bilirubin_min < 8.0 then 8\n when bilirubin_min >= 8.0 then 16\n end as bilirubin_score\n\n , case\n when glucose_min is null then null\n when glucose_min < 40 then 8\n when glucose_min < 60 then 9\n when glucose_min < 200 then 0\n when glucose_min < 350 then 3\n when glucose_min >= 350 then 5\n end as glucose_score\n\nfrom cohort\n)\n, score_max as\n(\n select cohort.subject_id, cohort.hadm_id, cohort.icustay_id\n , case\n when heartrate_max is null then null\n when heartrate_max < 40 then 8\n when heartrate_max < 50 then 5\n when heartrate_max < 100 then 0\n when heartrate_max < 110 then 1\n when heartrate_max < 120 then 5\n when heartrate_max < 140 then 7\n when heartrate_max < 155 then 13\n when heartrate_max >= 155 then 17\n end as hr_score\n\n , case\n when meanbp_max is null then null\n when meanbp_max < 40 then 23\n when meanbp_max < 60 then 15\n when meanbp_max < 70 then 7\n when meanbp_max < 80 then 6\n when meanbp_max < 100 then 0\n when meanbp_max < 120 then 4\n when meanbp_max < 130 then 7\n when meanbp_max < 140 then 9\n when meanbp_max >= 140 then 10\n end as meanbp_score\n\n
-- TODO: add 1 degree to axillary measurements\n , case\n when tempc_max is null then null\n when tempc_max < 33.0 then 20\n when tempc_max < 33.5 then 16\n when tempc_max < 34.0 then 13\n when tempc_max < 35.0 then 8\n when tempc_max < 36.0 then 2\n when tempc_max < 40.0 then 0\n when tempc_max >= 40.0 then 4\n end as temp_score\n\n , case\n when resprate_max is null then null\n -- special case for ventilated patients\n when vent = 1 and resprate_max < 14 then 0\n when resprate_max < 6 then 17\n when resprate_max < 12 then 8\n when resprate_max < 14 then 7\n when resprate_max < 25 then 0\n when resprate_max < 35 then 6\n when resprate_max < 40 then 9\n when resprate_max < 50 then 11\n when resprate_max >= 50 then 18\n end as resprate_score\n\n , case\n when hematocrit_max is null then null\n when hematocrit_max < 41.0 then 3\n when hematocrit_max < 50.0 then 0\n when hematocrit_max >= 50.0 then 3\n end as hematocrit_score\n\n , case\n when wbc_max is null then null\n when wbc_max < 1.0 then 19\n when wbc_max < 3.0 then 5\n when wbc_max < 20.0 then 0\n when wbc_max < 25.0 then 1\n when wbc_max >= 25.0 then 5\n end as wbc_score\n\n , case\n when creatinine_max is null then null\n when arf = 1 and creatinine_max < 1.5 then 0\n when arf = 1 and creatinine_max >= 1.5 then 10\n when creatinine_max < 0.5 then 3\n when creatinine_max < 1.5 then 0\n when creatinine_max < 1.95 then 4\n when creatinine_max >= 1.95 then 7\n end as creatinine_score\n\n , case\n when bun_max is null then null\n when bun_max < 17.0 then 0\n when bun_max < 20.0 then 2\n when bun_max < 40.0 then 7\n when bun_max < 80.0 then 11\n when bun_max >= 80.0 then 12\n end as bun_score\n\n , case\n when sodium_max is null then null\n when sodium_max < 120 then 3\n when sodium_max < 135 then 2\n when sodium_max < 155 then 0\n when sodium_max >= 155 then 4\n end as sodium_score\n\n , case\n when albumin_max is null then null\n when albumin_max < 2.0 then 11\n when albumin_max < 2.5 then 6\n when albumin_max < 4.5 then 0\n when albumin_max >= 4.5 then 4\n end as albumin_score\n\n , case\n when bilirubin_max is null then null\n when bilirubin_max < 2.0 then 0\n when bilirubin_max < 3.0 then 5\n when bilirubin_max < 5.0 then 6\n when bilirubin_max < 8.0 then 8\n when bilirubin_max >= 8.0 then 16\n end as bilirubin_score\n\n , case\n when glucose_max is null then null\n when glucose_max < 40 then 8\n when glucose_max < 60 then 9\n when glucose_max < 200 then 0\n when glucose_max < 350 then 3\n when glucose_max >= 350 then 5\n end as glucose_score\n\nfrom cohort\n)\n
-- Combine together the scores for min/max, using the following rules:\n-- 1) select the value furthest from a predefined normal value\n-- 2) if both equidistant, choose the one which gives a worse score\n-- 3) calculate score for acid-base abnormalities as it requires interactions\n-- sometimes the code is a bit redundant, i.e. we know the max would always be furthest from 0\n, scorecomp as\n(\n select co.*\n -- The rules for APS III require the definition of a \"worst\" value\n -- This value is defined as whatever value is furthest from a predefined normal\n -- e.g., for heart rate, worst is defined as furthest from 75\n , case\n when heartrate_max is null then null\n when abs(heartrate_max-75) > abs(heartrate_min-75)\n then smax.hr_score\n when abs(heartrate_max-75) < abs(heartrate_min-75)\n then smin.hr_score\n when abs(heartrate_max-75) = abs(heartrate_min-75)\n and smax.hr_score >= smin.hr_score\n then smax.hr_score\n when abs(heartrate_max-75) = abs(heartrate_min-75)\n and smax.hr_score < smin.hr_score\n then smin.hr_score\n end as hr_score\n\n , case\n when meanbp_max is null then null\n when abs(meanbp_max-90) > abs(meanbp_min-90)\n then smax.meanbp_score\n when abs(meanbp_max-90) < abs(meanbp_min-90)\n then smin.meanbp_score\n -- values are equidistant - pick the larger score\n when abs(meanbp_max-90) = abs(meanbp_min-90)\n and smax.meanbp_score >= smin.meanbp_score\n then smax.meanbp_score\n when abs(meanbp_max-90) = abs(meanbp_min-90)\n and smax.meanbp_score < smin.meanbp_score\n then smin.meanbp_score\n end as meanbp_score\n\n , case\n when tempc_max is null then null\n when abs(tempc_max-38) > abs(tempc_min-38)\n then smax.temp_score\n when abs(tempc_max-38) < abs(tempc_min-38)\n then smin.temp_score\n -- values are equidistant - pick the larger score\n when abs(tempc_max-38) = abs(tempc_min-38)\n and smax.temp_score >= smin.temp_score\n then smax.temp_score\n when abs(tempc_max-38) = abs(tempc_min-38)\n and smax.temp_score < smin.temp_score\n then smin.temp_score\n end as temp_score\n\n , case\n when resprate_max is null then null\n when abs(resprate_max-19) > abs(resprate_min-19)\n then smax.resprate_score\n when abs(resprate_max-19) < abs(resprate_min-19)\n then smin.resprate_score\n -- values are equidistant - pick the larger score\n when abs(resprate_max-19) = abs(resprate_max-19)\n and smax.resprate_score >= smin.resprate_score\n then smax.resprate_score\n when abs(resprate_max-19) = abs(resprate_max-19)\n and smax.resprate_score < smin.resprate_score\n then smin.resprate_score\n end as resprate_score\n\n , case\n when hematocrit_max is null then null\n when abs(hematocrit_max-45.5) > abs(hematocrit_min-45.5)\n then smax.hematocrit_score\n when abs(hematocrit_max-45.5) < abs(hematocrit_min-45.5)\n then smin.hematocrit_score\n
-- values are equidistant - pick the larger score\n when abs(hematocrit_max-45.5) = abs(hematocrit_max-45.5)\n and smax.hematocrit_score >= smin.hematocrit_score\n then smax.hematocrit_score\n when abs(hematocrit_max-45.5) = abs(hematocrit_max-45.5)\n and smax.hematocrit_score < smin.hematocrit_score\n then smin.hematocrit_score\n end as hematocrit_score\n\n , case\n when wbc_max is null then null\n when abs(wbc_max-11.5) > abs(wbc_min-11.5)\n then smax.wbc_score\n when abs(wbc_max-11.5) < abs(wbc_min-11.5)\n then smin.wbc_score\n -- values are equidistant - pick the larger score\n when abs(wbc_max-11.5) = abs(wbc_max-11.5)\n and smax.wbc_score >= smin.wbc_score\n then smax.wbc_score\n when abs(wbc_max-11.5) = abs(wbc_max-11.5)\n and smax.wbc_score < smin.wbc_score\n then smin.wbc_score\n end as wbc_score\n\n\n -- For some labs, \"furthest from normal\" doesn't make sense\n -- e.g. creatinine w/ ARF, the minimum could be 0.3, and the max 1.6\n -- while the minimum of 0.3 is \"further from 1\", seems like the max should be scored\n\n , case\n when creatinine_max is null then null\n -- if they have arf then use the max to score\n when arf = 1 then smax.creatinine_score\n -- otherwise furthest from 1\n when abs(creatinine_max-1) > abs(creatinine_min-1)\n then smax.creatinine_score\n when abs(creatinine_max-1) < abs(creatinine_min-1)\n then smin.creatinine_score\n -- values are equidistant\n when smax.creatinine_score >= smin.creatinine_score\n then smax.creatinine_score\n when smax.creatinine_score < smin.creatinine_score\n then smin.creatinine_score\n end as creatinine_score\n\n -- the rule for bun is the furthest from 0.. equivalent to the max value\n , case\n when bun_max is null then null\n else smax.bun_score\n end as bun_score\n\n , case\n when sodium_max is null then null\n when abs(sodium_max-145.5) > abs(sodium_min-145.5)\n then smax.sodium_score\n when abs(sodium_max-145.5) < abs(sodium_min-145.5)\n then smin.sodium_score\n -- values are equidistant - pick the larger score\n when abs(sodium_max-145.5) = abs(sodium_max-145.5)\n and smax.sodium_score >= smin.sodium_score\n then smax.sodium_score\n when abs(sodium_max-145.5) = abs(sodium_max-145.5)\n and smax.sodium_score < smin.sodium_score\n then smin.sodium_score\n end as sodium_score\n\n , case\n when albumin_max is null then null\n when abs(albumin_max-3.5) > abs(albumin_min-3.5)\n then smax.albumin_score\n when abs(albumin_max-3.5) < abs(albumin_min-3.5)\n then smin.albumin_score\n -- values are equidistant - pick the larger score\n when abs(albumin_max-3.5) = abs(albumin_max-3.5)\n and smax.albumin_score >= smin.albumin_score\n then smax.albumin_score\n when abs(albumin_max-3.5) = abs(albumin_max-3.5)\n and smax.albumin_score < smin.albumin_score\n then smin.albumin_score\n end as albumin_score\n\n , case\n when bilirubin_max is null then null\n else smax.bilirubin_score\n end as bilirubin_score\n\n , case\n when glucose_max is null then null\n when abs(glucose_max-130) > abs(glucose_min-130)\n then smax.glucose_score\n when abs(glucose_max-130) < abs(glucose_min-130)\n then smin.glucose_score\n
-- values are equidistant - pick the larger score\n when abs(glucose_max-130) = abs(glucose_max-130)\n and smax.glucose_score >= smin.glucose_score\n then smax.glucose_score\n when abs(glucose_max-130) = abs(glucose_max-130)\n and smax.glucose_score < smin.glucose_score\n then smin.glucose_score\n end as glucose_score\n\n\n -- Below are interactions/special cases where only 1 value is important\n , case\n when urineoutput is null then null\n when urineoutput < 400 then 15\n when urineoutput < 600 then 8\n when urineoutput < 900 then 7\n when urineoutput < 1500 then 5\n when urineoutput < 2000 then 4\n when urineoutput < 4000 then 0\n when urineoutput >= 4000 then 1\n end as uo_score\n\n , case\n when endotrachflag = 1\n -- here they are intubated, so their verbal score is inappropriate\n -- normally you are supposed to use \"clinical judgement\"\n -- we don't have that, so we just assume normal (as was done in the original study)\n then 0\n when gcseyes = 1\n then case\n when gcsverbal = 1 and gcsmotor in (1,2)\n then 48\n when gcsverbal = 1 and gcsmotor in (3,4)\n then 33\n when gcsverbal = 1 and gcsmotor in (5,6)\n then 16\n when gcsverbal in (2,3) and gcsmotor in (1,2)\n then 29\n when gcsverbal in (2,3) and gcsmotor in (3,4)\n then 24\n when gcsverbal in (2,3) and gcsmotor >= 5\n -- highly unlikely clinical combination\n then null\n when gcsverbal >= 4\n then null\n end\n when gcseyes > 1\n then case\n when gcsverbal = 1 and gcsmotor in (1,2)\n then 29\n when gcsverbal = 1 and gcsmotor in (3,4)\n then 24\n when gcsverbal = 1 and gcsmotor in (5,6)\n then 15\n when gcsverbal in (2,3) and gcsmotor in (1,2)\n then 29\n when gcsverbal in (2,3) and gcsmotor in (3,4)\n then 24\n when gcsverbal in (2,3) and gcsmotor = 5\n then 13\n when gcsverbal in (2,3) and gcsmotor = 6\n then 10\n when gcsverbal = 4 and gcsmotor in (1,2,3,4)\n then 13\n when gcsverbal = 4 and gcsmotor = 5\n then 8\n when gcsverbal = 4 and gcsmotor = 6\n then 3\n when gcsverbal = 5 and gcsmotor in (1,2,3,4,5)\n then 3\n when gcsverbal = 5 and gcsmotor = 6\n then 0\n end\n else null\n end as gcs_score\n\n , case\n when pao2 is null and aado2 is null\n then null\n when pao2 is not null then\n case\n when pao2 < 50 then 15\n when pao2 < 70 then 5\n when pao2 < 80 then 2\n else 0 end\n when aado2 is not null then\n case\n when aado2 < 100 then 0\n when aado2 < 250 then 7\n when aado2 < 350 then 9\n when aado2 < 500 then 11\n when aado2 >= 500 then 14\n else 0 end\n end as pao2_aado2_score\n\nfrom cohort co\nleft join score_min smin\n on co.icustay_id = smin.icustay_id\nleft join score_max smax\n on co.icustay_id = smax.icustay_id\n)\n
-- tabulate the APS III using the scores from the worst values\n, score as\n(\n select s.*\n -- coalesce statements impute normal score of zero if data element is missing\n , coalesce(hr_score,0)\n + coalesce(meanbp_score,0)\n + coalesce(temp_score,0)\n + coalesce(resprate_score,0)\n + coalesce(pao2_aado2_score,0)\n + coalesce(hematocrit_score,0)\n + coalesce(wbc_score,0)\n + coalesce(creatinine_score,0)\n + coalesce(uo_score,0)\n + coalesce(bun_score,0)\n + coalesce(sodium_score,0)\n + coalesce(albumin_score,0)\n + coalesce(bilirubin_score,0)\n + coalesce(glucose_score,0)\n + coalesce(acidbase_score,0)\n + coalesce(gcs_score,0)\n as apsiii\n from scorecomp s\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n, apsiii\n-- Calculate probability of hospital mortality using equation from Johnson 2014.\n, 1 / (1 + exp(- (-4.4360 + 0.04726*(apsiii) ))) as apsiii_prob\n, hr_score\n, meanbp_score\n, temp_score\n, resprate_score\n, pao2_aado2_score\n, hematocrit_score\n, wbc_score\n, creatinine_score\n, uo_score\n, bun_score\n, sodium_score\n, albumin_score\n, bilirubin_score\n, glucose_score\n, acidbase_score\n, gcs_score\nFROM icustays ie\nleft join score s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_apsiii\nowner to postgres;"
lods <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_lods;\ncreate materialized view mimic3.severityscores_lods\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Logistic Organ Dysfunction Score (LODS)\n-- This query extracts the logistic organ dysfunction system.\n-- This score is a measure of organ failure in a patient.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for lods:\n-- Le Gall, J. R., Klar, J., Lemeshow, S., Saulnier, F., Alberti, C., Artigas, A., & Teres, D.\n-- The Logistic Organ Dysfunction system: a new way to assess organ dysfunction in the intensive care unit.\n-- JAMA 276.10 (1996): 802-810.\n\n-- Variables used in lods:\n-- gcs\n-- VITALS: Heart rate, systolic blood pressure\n-- FLAGS: ventilation/cpap\n-- IO: urine output\n-- LABS: blood urea nitrogen, wbc, bilirubin, creatinine, prothrombin time (PT), platelets\n-- ABG: PaO2 with associated FiO2\n\n-- The following views are required to run this query:\n-- 1) firstday_urine_output - generated by urine-output-first-day.sql\n-- 2) durations_ventilation_durations - generated by durations_ventilation_durations.sql\n-- 3) firstday_vitals - generated by vitals-first-day.sql\n-- 4) firstday_gcs - generated by gcs-first-day.sql\n-- 5) firstday_labs - generated by labs-first-day.sql\n-- 5) firstday_blood_gas_arterial - generated by blood-gas-first-day-arterial.sql\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n-- extract CPAP from the \"Oxygen Delivery Device\" fields\nwith cpap as\n(\n select ie.icustay_id\n , min(DATETIME_SUB(charttime, INTERVAL '1' HOUR)) as starttime\n , max(DATETIME_ADD(charttime, INTERVAL '4' HOUR)) as endtime\n , max(CASE\n WHEN lower(ce.value) LIKE '%cpap%' THEN 1\n WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1\n else 0 end) as cpap\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where itemid in\n (\n -- TODO: when metavision data import fixed, check the values in 226732 match the value clause below\n 467, 469, 226732\n )\n and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%')\n -- exclude rows marked as error\n AND (ce.error IS NULL OR ce.error = 0)\n group by ie.icustay_id\n)\n, pafi1 as\n(\n -- join blood gas to ventilation durations to determine if patient was vent\n
-- also join to cpap table for the same purpose\n select bg.icustay_id, bg.charttime\n , pao2fio2\n , case when vd.icustay_id is not null then 1 else 0 end as vent\n , case when cp.icustay_id is not null then 1 else 0 end as cpap\n from firstday_blood_gas_arterial bg\n left join durations_ventilation_durations vd\n on bg.icustay_id = vd.icustay_id\n and bg.charttime >= vd.starttime\n and bg.charttime <= vd.endtime\n left join cpap cp\n on bg.icustay_id = cp.icustay_id\n and bg.charttime >= cp.starttime\n and bg.charttime <= cp.endtime\n)\n, pafi2 as\n(\n -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients*\n select icustay_id\n , min(pao2fio2) as pao2fio2_vent_min\n from pafi1\n where vent = 1 or cpap = 1\n group by icustay_id\n)\n, cohort as\n(\nselect ie.subject_id\n , ie.hadm_id\n , ie.icustay_id\n , ie.intime\n , ie.outtime\n\n , gcs.mingcs\n , vital.heartrate_max\n , vital.heartrate_min\n , vital.sysbp_max\n , vital.sysbp_min\n\n -- this value is non-null iff the patient is on vent/cpap\n , pf.pao2fio2_vent_min\n\n , labs.bun_max\n , labs.bun_min\n , labs.wbc_max\n , labs.wbc_min\n , labs.bilirubin_max\n , labs.creatinine_max\n , labs.pt_min\n , labs.pt_max\n , labs.platelet_min\n\n , uo.urineoutput\n\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\n\n-- join to above view to get pao2/fio2 ratio\nleft join pafi2 pf\n on ie.icustay_id = pf.icustay_id\n\n-- join to custom tables to get more data....\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\nleft join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n)\n, scorecomp as\n(\nselect\n cohort.*\n -- Below code calculates the component scores needed for severityscores_saps\n\n -- neurologic\n , case\n when mingcs is null then null\n when mingcs < 3 then null -- erroneous value/on trach\n when mingcs <= 5 then 5\n when mingcs <= 8 then 3\n when mingcs <= 13 then 1\n else 0\n end as neurologic\n\n -- cardiovascular\n , case\n when heartrate_max is null\n and sysbp_min is null then null\n when heartrate_min < 30 then 5\n when sysbp_min < 40 then 5\n when sysbp_min < 70 then 3\n when sysbp_max >= 270 then 3\n when heartrate_max >= 140 then 1\n when sysbp_max >= 240 then 1\n when sysbp_min < 90 then 1\n else 0\n end as cardiovascular\n\n -- renal\n , case\n when bun_max is null\n or urineoutput is null\n or creatinine_max is null\n then null\n when urineoutput < 500.0 then 5\n when bun_max >= 56.0 then 5\n when creatinine_max >= 1.60 then 3\n when urineoutput < 750.0 then 3\n when bun_max >= 28.0 then 3\n when urineoutput >= 10000.0 then 3\n when creatinine_max >= 1.20 then 1\n when bun_max >= 17.0 then 1\n when bun_max >= 7.50 then 1\n else 0\n end as renal\n\n
-- pulmonary\n , case\n when pao2fio2_vent_min is null then 0\n when pao2fio2_vent_min >= 150 then 1\n when pao2fio2_vent_min < 150 then 3\n else null\n end as pulmonary\n\n -- hematologic\n , case\n when wbc_max is null\n and platelet_min is null\n then null\n when wbc_min < 1.0 then 3\n when wbc_min < 2.5 then 1\n when platelet_min < 50.0 then 1\n when wbc_max >= 50.0 then 1\n else 0\n end as hematologic\n\n -- hepatic\n -- We have defined the \"standard\" PT as 12 seconds.\n -- This is an assumption and subsequent analyses may be affected by this assumption.\n , case\n when pt_max is null\n and bilirubin_max is null\n then null\n when bilirubin_max >= 2.0 then 1\n when pt_max > (12+3) then 1\n when pt_min < (12*0.25) then 1\n else 0\n end as hepatic\n\nfrom cohort\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n-- coalesce statements impute normal score of zero if data element is missing\n, coalesce(neurologic,0)\n+ coalesce(cardiovascular,0)\n+ coalesce(renal,0)\n+ coalesce(pulmonary,0)\n+ coalesce(hematologic,0)\n+ coalesce(hepatic,0)\n as lods\n, neurologic\n, cardiovascular\n, renal\n, pulmonary\n, hematologic\n, hepatic\nFROM icustays ie\nleft join scorecomp s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_lods\nowner to postgres;"
mlods <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_mlods;\ncreate materialized view mimic3.severityscores_mlods\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Modified Logistic organ dysfunction system (mLODS)\n-- This query extracts a modified version of the logistic organ dysfunction system.\n-- This score was used in the third international definition of sepsis: Sepsis-3.\n-- This score is a measure of organ failure in a patient.\n-- ------------------------------------------------------------------\n\n-- Reference for lods:\n-- Le Gall, J. R., Klar, J., Lemeshow, S., Saulnier, F., Alberti, C., Artigas, A., & Teres, D.\n-- The Logistic Organ Dysfunction system: a new way to assess organ dysfunction in the intensive care unit.\n-- JAMA 276.10 (1996): 802-810.\n\n-- Reference for modified lods:\n-- Le Gall, J. R., Klar, J., Lemeshow, S., Saulnier, F., Alberti, C., Artigas, A., & Teres, D.\n-- The Logistic Organ Dysfunction system: a new way to assess organ dysfunction in the intensive care unit.\n-- JAMA 276.10 (1996): 802-810.\n\n-- Variables used in mlods:\n-- gcs\n-- VITALS: Heart rate, systolic blood pressure\n-- FLAGS: ventilation/cpap\n-- LABS: wbc, bilirubin, creatinine, platelets\n-- ABG: PaO2 with associated FiO2\n\n-- Variables *excluded*, that are used in the original lods:\n-- prothrombin time (PT), blood urea nitrogen, urine output\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n-- extract CPAP from the \"Oxygen Delivery Device\" fields\nwith cpap as\n(\n select ie.icustay_id\n , min(DATETIME_SUB(charttime, INTERVAL '1' HOUR)) as starttime\n , max(DATETIME_ADD(charttime, INTERVAL '4' HOUR)) as endtime\n , max(CASE\n WHEN lower(ce.value) LIKE '%cpap%' THEN 1\n WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1\n else 0 end) as cpap\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and ie.outtime\n where itemid in\n (\n -- TODO: when metavision data import fixed, check the values in 226732 match the value clause below\n 467, 469, 226732\n )\n and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%')\n -- exclude rows marked as error\n AND (ce.error IS NULL OR ce.error = 0)\n group by ie.icustay_id\n)\n, pafi1 as\n(\n -- join blood gas to ventilation durations to determine if patient was vent\n -- also join to cpap table for the same purpose\n select bg.icustay_id, bg.charttime\n , PaO2FiO2\n , case when vd.icustay_id is not null then 1 else 0 end as vent\n , case when cp.icustay_id is not null then 1 else 0 end as cpap\n from firstday_blood_gas_arterial bg\n left join durations_ventilation_durations vd\n on bg.icustay_id = vd.icustay_id\n and bg.charttime >= vd.starttime\n and bg.charttime <= vd.endtime\n left join cpap cp\n on bg.icustay_id = cp.icustay_id\n and bg.charttime >= cp.starttime\n and bg.charttime <= cp.endtime\n)\n, pafi2 as\n(\n -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients*\n select icustay_id\n , min(PaO2FiO2) as PaO2FiO2_vent_min\n from pafi1\n where vent = 1 or cpap = 1\n group by icustay_id\n)\n, cohort as\n(\nselect ie.subject_id\n , ie.hadm_id\n , ie.icustay_id\n , ie.intime\n , ie.outtime\n\n , gcs.mingcs\n , vital.heartrate_max\n , vital.heartrate_min\n , vital.sysbp_max\n , vital.sysbp_min\n\n
-- this value is non-null iff the patient is on vent/cpap\n , pf.PaO2FiO2_vent_min\n\n , labs.wbc_max\n , labs.wbc_min\n , labs.bilirubin_max\n , labs.creatinine_max\n , labs.platelet_min\n\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\n\n-- join to above view to get pao2/fio2 ratio\nleft join pafi2 pf\n on ie.icustay_id = pf.icustay_id\n\n-- join to custom tables to get more data....\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n)\n, scorecomp as\n(\nselect\n cohort.*\n\n -- neurologic\n , case\n when mingcs is null then null\n when mingcs < 3 then null -- erroneous value/on trach\n when mingcs <= 5 then 5\n when mingcs <= 8 then 3\n when mingcs <= 13 then 1\n else 0\n end as neurologic\n\n -- cardiovascular\n , case\n when heartrate_max is null\n and sysbp_min is null then null\n when heartrate_min < 30 then 5\n when sysbp_min < 40 then 5\n when sysbp_min < 70 then 3\n when sysbp_max >= 270 then 3\n when heartrate_max >= 140 then 1\n when sysbp_max >= 240 then 1\n when sysbp_min < 90 then 1\n else 0\n end as cardiovascular\n\n -- renal\n , case\n when creatinine_max is null\n -- or UrineOutput is null\n -- or bun_max is null\n then null\n -- when UrineOutput < 500.0 then 5\n -- when bun_max >= 56.0 then 5\n when creatinine_max >= 1.60 then 3\n -- when UrineOutput < 750.0 then 3\n -- when bun_max >= 28.0 then 3\n -- when UrineOutput >= 10000.0 then 3\n when creatinine_max >= 1.20 then 1\n -- when bun_max >= 17.0 then 1\n -- when bun_max >= 7.50 then 1\n else 0\n end as renal\n\n -- pulmonary\n , case\n when PaO2FiO2_vent_min is null then 0\n when PaO2FiO2_vent_min >= 150 then 1\n when PaO2FiO2_vent_min < 150 then 3\n else null\n end as pulmonary\n\n -- hematologic\n , case\n when wbc_max is null\n and platelet_min is null\n then null\n when wbc_min < 1.0 then 3\n when wbc_min < 2.5 then 1\n when platelet_min < 50.0 then 1\n when wbc_max >= 50.0 then 1\n else 0\n end as hematologic\n\n -- hepatic\n , case\n when bilirubin_max is null\n -- and pt_max is null\n then null\n when bilirubin_max >= 2.0 then 1\n -- when pt_max > (12+3) then 1\n -- when pt_min < (12*0.25) then 1\n else 0\n end as hepatic\n\nfrom cohort\n)\nselect ie.icustay_id\n-- coalesce statements impute normal score of zero if data element is missing\n, coalesce(neurologic,0)\n+ coalesce(cardiovascular,0)\n+ coalesce(renal,0)\n+ coalesce(pulmonary,0)\n+ coalesce(hematologic,0)\n+ coalesce(hepatic,0)\n as mlods\n, neurologic\n, cardiovascular\n, renal\n, pulmonary\n, hematologic\n, hepatic\nFROM icustays ie\nleft join scorecomp s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_mlods\nowner to postgres;"
oasis <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_oasis;\ncreate materialized view mimic3.severityscores_oasis\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Oxford Acute Severity of Illness Score (oasis)\n-- This query extracts the Oxford acute severity of illness score.\n-- This score is a measure of severity of illness for patients in the ICU.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for oasis:\n-- Johnson, Alistair EW, Andrew A. Kramer, and Gari D. Clifford.\n-- \"A new severity of illness scale using a subset of acute physiology and chronic health evaluation data elements shows comparable predictive accuracy*.\"\n-- Critical care medicine 41, no. 7 (2013): 1711-1718.\n\n-- Variables used in oasis:\n-- Heart rate, gcs, MAP, temperature, Respiratory rate, Ventilation status (sourced FROM chartevents)\n-- Urine output (sourced from OUTPUTEVENTS)\n-- Elective surgery (sourced FROM admissions and SERVICES)\n-- Pre-ICU in-hospital length of stay (sourced FROM admissions and ICUSTAYS)\n-- Age (sourced FROM patients)\n\n-- The following views are required to run this query:\n-- 1) firstday_urine_output - generated by urine-output-first-day.sql\n-- 2) vent_first_day - generated by ventilated-first-day.sql\n-- 3) firstday_vitals - generated by vitals-first-day.sql\n-- 4) firstday_gcs - generated by gcs-first-day.sql\n\n\n-- Regarding missing values:\n-- The ventilation flag is always 0/1. It cannot be missing, since VENT=0 if no data is found for vent settings.\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n\nwith surgflag as\n(\n select ie.icustay_id\n , max(case\n when lower(curr_service) like '%surg%' then 1\n when curr_service = 'ORTHO' then 1\n else 0 end) as surgical\n FROM icustays ie\n left join services se\n on ie.hadm_id = se.hadm_id\n and se.transfertime < DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n group by ie.icustay_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n , ie.intime\n , ie.outtime\n , adm.deathtime\n , datetime_diff(ie.intime, adm.admittime,'MINUTE') as preiculos\n , datetime_diff(ie.intime, pat.dob,'YEAR') as age\n , gcs.mingcs\n , vital.heartrate_max\n , vital.heartrate_min\n , vital.meanbp_max\n , vital.meanbp_min\n , vital.resprate_max\n , vital.resprate_min\n , vital.tempc_max\n , vital.tempc_min\n , vent.vent as mechvent\n , uo.urineoutput\n\n , case\n when adm.ADMISSION_TYPE = 'ELECTIVE' and sf.surgical = 1\n then 1\n when adm.ADMISSION_TYPE is null or sf.surgical is null\n then null\n else 0\n end as electivesurgery\n\n
-- age group\n , case\n when datetime_diff(ie.intime, pat.dob,'YEAR') <= 1 then 'neonate'\n when datetime_diff(ie.intime, pat.dob,'YEAR') <= 15 then 'middle'\n else 'adult' end as icustay_age_group\n\n -- mortality flags\n , case\n when adm.deathtime between ie.intime and ie.outtime\n then 1\n when adm.deathtime <= ie.intime -- sometimes there are typographical errors in the death date\n then 1\n when adm.dischtime <= ie.outtime and adm.discharge_location = 'DEAD/EXPIRED'\n then 1\n else 0 end\n as icustay_expire_flag\n , adm.hospital_expire_flag\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\nleft join surgflag sf\n on ie.icustay_id = sf.icustay_id\n-- join to custom tables to get more data....\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\nleft join firstday_ventilation vent\n on ie.icustay_id = vent.icustay_id\n)\n, scorecomp as\n(\nselect co.subject_id, co.hadm_id, co.icustay_id\n, co.icustay_age_group\n, co.icustay_expire_flag\n, co.hospital_expire_flag\n\n-- Below code calculates the component scores needed for oasis\n, case when preiculos is null then null\n when preiculos < 10.2 then 5\n when preiculos < 297 then 3\n when preiculos < 1440 then 0\n when preiculos < 18708 then 1\n else 2 end as preiculos_score\n, case when age is null then null\n when age < 24 then 0\n when age <= 53 then 3\n when age <= 77 then 6\n when age <= 89 then 9\n when age >= 90 then 7\n else 0 end as age_score\n, case when mingcs is null then null\n when mingcs <= 7 then 10\n when mingcs < 14 then 4\n when mingcs = 14 then 3\n else 0 end as gcs_score\n, case when heartrate_max is null then null\n when heartrate_max > 125 then 6\n when heartrate_min < 33 then 4\n when heartrate_max >= 107 and heartrate_max <= 125 then 3\n when heartrate_max >= 89 and heartrate_max <= 106 then 1\n else 0 end as heartrate_score\n, case when meanbp_min is null then null\n when meanbp_min < 20.65 then 4\n when meanbp_min < 51 then 3\n when meanbp_max > 143.44 then 3\n when meanbp_min >= 51 and meanbp_min < 61.33 then 2\n else 0 end as meanbp_score\n, case when resprate_min is null then null\n when resprate_min < 6 then 10\n when resprate_max > 44 then 9\n when resprate_max > 30 then 6\n when resprate_max > 22 then 1\n when resprate_min < 13 then 1 else 0\n end as resprate_score\n, case when tempc_max is null then null\n when tempc_max > 39.88 then 6\n when tempc_min >= 33.22 and tempc_min <= 35.93 then 4\n when tempc_max >= 33.22 and tempc_max <= 35.93 then 4\n when tempc_min < 33.22 then 3\n when tempc_min > 35.93 and tempc_min <= 36.39 then 2\n when tempc_max >= 36.89 and tempc_max <= 39.88 then 2\n else 0 end as temp_score\n, case when UrineOutput is null then null\n when UrineOutput < 671.09 then 10\n when UrineOutput > 6896.80 then 8\n when UrineOutput >= 671.09\n and UrineOutput <= 1426.99 then 5\n when UrineOutput >= 1427.00\n and UrineOutput <= 2544.14 then 1\n else 0 end as urineoutput_score\n, case when mechvent is null then null\n when mechvent = 1 then 9\n else 0 end as mechvent_score\n, case when electivesurgery is null then null\n when electivesurgery = 1 then 0\n else 6 end as electivesurgery_score\n\n\n
-- The below code gives the component associated with each score\n-- This is not needed to calculate oasis, but provided for user convenience.\n-- If both the min/max are in the normal range (score of 0), then the average value is stored.\n, preiculos\n, age\n, mingcs as gcs\n, case when heartrate_max is null then null\n when heartrate_max > 125 then heartrate_max\n when heartrate_min < 33 then heartrate_min\n when heartrate_max >= 107 and heartrate_max <= 125 then heartrate_max\n when heartrate_max >= 89 and heartrate_max <= 106 then heartrate_max\n else (heartrate_min+heartrate_max)/2 end as heartrate\n, case when meanbp_min is null then null\n when meanbp_min < 20.65 then meanbp_min\n when meanbp_min < 51 then meanbp_min\n when meanbp_max > 143.44 then meanbp_max\n when meanbp_min >= 51 and meanbp_min < 61.33 then meanbp_min\n else (meanbp_min+meanbp_max)/2 end as meanbp\n, case when resprate_min is null then null\n when resprate_min < 6 then resprate_min\n when resprate_max > 44 then resprate_max\n when resprate_max > 30 then resprate_max\n when resprate_max > 22 then resprate_max\n when resprate_min < 13 then resprate_min\n else (resprate_min+resprate_max)/2 end as resprate\n, case when tempc_max is null then null\n when tempc_max > 39.88 then tempc_max\n when tempc_min >= 33.22 and tempc_min <= 35.93 then tempc_min\n when tempc_max >= 33.22 and tempc_max <= 35.93 then tempc_max\n when tempc_min < 33.22 then tempc_min\n when tempc_min > 35.93 and tempc_min <= 36.39 then tempc_min\n when tempc_max >= 36.89 and tempc_max <= 39.88 then tempc_max\n else (tempc_min+tempc_max)/2 end as temp\n, UrineOutput\n, mechvent\n, electivesurgery\nfrom cohort co\n)\n, score as\n(\nselect s.*\n , coalesce(age_score,0)\n + coalesce(preiculos_score,0)\n + coalesce(gcs_score,0)\n + coalesce(heartrate_score,0)\n + coalesce(meanbp_score,0)\n + coalesce(resprate_score,0)\n + coalesce(temp_score,0)\n + coalesce(urineoutput_score,0)\n + coalesce(mechvent_score,0)\n + coalesce(electivesurgery_score,0)\n as oasis\nfrom scorecomp s\n)\nselect\n subject_id, hadm_id, icustay_id\n , icustay_age_group\n , hospital_expire_flag\n , icustay_expire_flag\n , oasis\n -- Calculate the probability of in-hospital mortality\n , 1 / (1 + exp(- (-6.1746 + 0.1275*(oasis) ))) as oasis_PROB\n , age, age_score\n , preiculos, preiculos_score\n , gcs, gcs_score\n , heartrate, heartrate_score\n , meanbp, meanbp_score\n , resprate, resprate_score\n , temp, temp_score\n , urineoutput, urineoutput_score\n , mechvent, mechvent_score\n , electivesurgery, electivesurgery_score\nfrom score\norder by icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_oasis\nowner to postgres;"
qsofa <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_qsofa;\ncreate materialized view mimic3.severityscores_qsofa\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Quick Sequential Organ Failure Assessment (qSOFA)\n-- This query extracts the quick sequential organ failure assessment.\n-- This score was a recent revision of sofa, aiming to detect patients at risk of sepsis.\n-- The score is calculated on the first day of each ICU patients' stay - though needn't be.\n-- ------------------------------------------------------------------\n\n-- Reference for qsofa:\n-- Singer M, et al. The Third International Consensus Definitions for Sepsis and Septic Shock (Sepsis-3)\n-- Seymour CW, et al. Assessment of Clinical Criteria for Sepsis: For the Third International Consensus Definitions for Sepsis and Septic Shock (Sepsis-3)\n\n-- Variables used in qsofa:\n-- gcs, respiratory rate, systolic blood pressure\n\n-- The following views required to run this query:\n-- 1) gcsfirstday - generated by gcs-first-day.sql\n-- 2) vitalsfirstday - generated by vitals-first-day.sql\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\nwith scorecomp as\n(\nselect ie.icustay_id\n , v.sysbp_min\n , v.resprate_max\n , gcs.mingcs\nFROM icustays ie\nleft join firstday_vitals v\n on ie.icustay_id = v.icustay_id\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\n)\n, scorecalc as\n(\n -- Calculate the final score\n -- note that if the underlying data is missing, the component is null\n -- eventually these are treated as 0 (normal), but knowing when data is missing is useful for debugging\n select icustay_id\n , case\n when sysbp_min is null then null\n when sysbp_min <= 100 then 1\n else 0 end\n as sysbp_score\n , case\n when mingcs is null then null\n when mingcs <= 13 then 1\n else 0 end\n as gcs_score\n , case\n when resprate_max is null then null\n when resprate_max >= 22 then 1\n else 0 end\n as resprate_score\n from scorecomp\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n, coalesce(sysbp_score,0)\n + coalesce(gcs_score,0)\n + coalesce(resprate_score,0)\n as qsofa\n, sysbp_score\n, gcs_score\n, resprate_score\nFROM icustays ie\nleft join scorecalc s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_qsofa\nowner to postgres;"
saps <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_saps;\ncreate materialized view mimic3.severityscores_saps\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Simplified Acute Physiology Score (SAPS)\n-- This query extracts the simplified acute physiology score.\n-- This score is a measure of patient severity of illness.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for saps:\n-- Jean-Roger Le Gall, Philippe Loirat, Annick Alperovitch, Paul Glaser, Claude Granthil,\n-- Daniel Mathieu, Philippe Mercier, Remi Thomas, and Daniel Villers.\n-- \"A simplified acute physiology score for ICU patients.\"\n-- Critical care medicine 12, no. 11 (1984): 975-977.\n\n-- Variables used in saps:\n-- Age, gcs\n-- VITALS: Heart rate, systolic blood pressure, temperature, respiration rate\n-- FLAGS: ventilation/cpap\n-- IO: urine output\n-- LABS: blood urea nitrogen, hematocrit, wbc, glucose, potassium, sodium, hco3\n\n-- The following views are required to run this query:\n-- 1) firstday_urine_output - generated by urine-output-first-day.sql\n-- 2) vent_first_day - generated by ventilated-first-day.sql\n-- 3) firstday_vitals - generated by vitals-first-day.sql\n-- 4) firstday_gcs - generated by gcs-first-day.sql\n-- 5) firstday_labs - generated by labs-first-day.sql\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n-- extract CPAP from the \"Oxygen Delivery Device\" fields\nwith cpap as\n(\n select ie.icustay_id\n , max(CASE\n WHEN lower(ce.value) LIKE '%cpap%' THEN 1\n WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1\n else 0 end) as cpap\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where itemid in\n (\n -- TODO: when metavision data import fixed, check the values in 226732 match the value clause below\n 467, 469, 226732\n )\n and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%')\n -- exclude rows marked as error\n AND (ce.error IS NULL OR ce.error = 0)\n group by ie.icustay_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n , ie.intime\n , ie.outtime\n\n -- the casts ensure the result is numeric.. we could equally extract EPOCH from the interval\n
-- however this code works in Oracle and Postgres\n , datetime_diff(ie.intime, pat.dob,'YEAR') as age\n , gcs.mingcs\n , vital.heartrate_max\n , vital.heartrate_min\n , vital.sysbp_max\n , vital.sysbp_min\n , vital.resprate_max\n , vital.resprate_min\n , vital.tempc_max\n , vital.tempc_min\n\n , coalesce(vital.glucose_max, labs.glucose_max) as glucose_max\n , coalesce(vital.glucose_min, labs.glucose_min) as glucose_min\n\n , labs.bun_max\n , labs.bun_min\n , labs.hematocrit_max\n , labs.hematocrit_min\n , labs.wbc_max\n , labs.wbc_min\n , labs.sodium_max\n , labs.sodium_min\n , labs.potassium_max\n , labs.potassium_min\n , labs.bicarbonate_max\n , labs.bicarbonate_min\n\n , vent.vent as mechvent\n , uo.urineoutput\n\n , cp.cpap\n\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\n\n-- join to above view to get CPAP\nleft join cpap cp\n on ie.icustay_id = cp.icustay_id\n\n-- join to custom tables to get more data....\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\nleft join firstday_ventilation vent\n on ie.icustay_id = vent.icustay_id\nleft join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n)\n, scorecomp as\n(\nselect\n cohort.*\n
-- Below code calculates the component scores needed for saps\n , case\n when age is null then null\n when age <= 45 then 0\n when age <= 55 then 1\n when age <= 65 then 2\n when age <= 75 then 3\n when age > 75 then 4\n end as age_score\n , case\n when heartrate_max is null then null\n when heartrate_max >= 180 then 4\n when heartrate_min < 40 then 4\n when heartrate_max >= 140 then 3\n when heartrate_min <= 54 then 3\n when heartrate_max >= 110 then 2\n when heartrate_min <= 69 then 2\n when heartrate_max >= 70 and heartrate_max <= 109\n and heartrate_min >= 70 and heartrate_min <= 109\n then 0\n end as hr_score\n , case\n when sysbp_min is null then null\n when sysbp_max >= 190 then 4\n when sysbp_min < 55 then 4\n when sysbp_max >= 150 then 2\n when sysbp_min <= 79 then 2\n when sysbp_max >= 80 and sysbp_max <= 149\n and sysbp_min >= 80 and sysbp_min <= 149\n then 0\n end as sysbp_score\n\n , case\n when tempc_max is null then null\n when tempc_max >= 41.0 then 4\n when tempc_min < 30.0 then 4\n when tempc_max >= 39.0 then 3\n when tempc_min <= 31.9 then 3\n when tempc_min <= 33.9 then 2\n when tempc_max > 38.4 then 1\n when tempc_min < 36.0 then 1\n when tempc_max >= 36.0 and tempc_max <= 38.4\n and tempc_min >= 36.0 and tempc_min <= 38.4\n then 0\n end as temp_score\n\n , case\n when resprate_min is null then null\n when resprate_max >= 50 then 4\n when resprate_min < 6 then 4\n when resprate_max >= 35 then 3\n when resprate_min <= 9 then 2\n when resprate_max >= 25 then 1\n when resprate_min <= 11 then 1\n when resprate_max >= 12 and resprate_max <= 24\n and resprate_min >= 12 and resprate_min <= 24\n then 0\n end as resp_score\n\n , case\n when coalesce(mechvent,cpap) is null then null\n when cpap = 1 then 3\n when mechvent = 1 then 3\n else 0\n end as vent_score\n\n , case\n when UrineOutput is null then null\n when UrineOutput > 5000.0 then 2\n when UrineOutput >= 3500.0 then 1\n when UrineOutput >= 700.0 then 0\n when UrineOutput >= 500.0 then 2\n when UrineOutput >= 200.0 then 3\n when UrineOutput < 200.0 then 4\n end as uo_score\n\n , case\n when bun_max is null then null\n when bun_max >= 55.0 then 4\n when bun_max >= 36.0 then 3\n when bun_max >= 29.0 then 2\n when bun_max >= 7.50 then 1\n when bun_min < 3.5 then 1\n when bun_max >= 3.5 and bun_max < 7.5\n and bun_min >= 3.5 and bun_min < 7.5\n then 0\n end as bun_score\n\n , case\n when hematocrit_max is null then null\n when hematocrit_max >= 60.0 then 4\n when hematocrit_min < 20.0 then 4\n when hematocrit_max >= 50.0 then 2\n when hematocrit_min < 30.0 then 2\n when hematocrit_max >= 46.0 then 1\n when hematocrit_max >= 30.0 and hematocrit_max < 46.0\n and hematocrit_min >= 30.0 and hematocrit_min < 46.0\n then 0\n end as hematocrit_score\n\n , case\n when wbc_max is null then null\n when wbc_max >= 40.0 then 4\n when wbc_min < 1.0 then 4\n when wbc_max >= 20.0 then 2\n when wbc_min < 3.0 then 2\n when wbc_max >= 15.0 then 1\n when wbc_max >= 3.0 and wbc_max < 15.0\n and wbc_min >= 3.0 and wbc_min < 15.0\n then 0\n end as wbc_score\n\n ,
case\n when glucose_max is null then null\n when glucose_max >= 44.5 then 4\n when glucose_min < 1.6 then 4\n when glucose_max >= 27.8 then 3\n when glucose_min < 2.8 then 3\n when glucose_min < 3.9 then 2\n when glucose_max >= 14.0 then 1\n when glucose_max >= 3.9 and glucose_max < 14.0\n and glucose_min >= 3.9 and glucose_min < 14.0\n then 0\n end as glucose_score\n\n , case\n when potassium_max is null then null\n when potassium_max >= 7.0 then 4\n when potassium_min < 2.5 then 4\n when potassium_max >= 6.0 then 3\n when potassium_min < 3.0 then 2\n when potassium_max >= 5.5 then 1\n when potassium_min < 3.5 then 1\n when potassium_max >= 3.5 and potassium_max < 5.5\n and potassium_min >= 3.5 and potassium_min < 5.5\n then 0\n end as potassium_score\n\n , case\n when sodium_max is null then null\n when sodium_max >= 180 then 4\n when sodium_min < 110 then 4\n when sodium_max >= 161 then 3\n when sodium_min < 120 then 3\n when sodium_max >= 156 then 2\n when sodium_min < 130 then 2\n when sodium_max >= 151 then 1\n when sodium_max >= 130 and sodium_max < 151\n and sodium_min >= 130 and sodium_min < 151\n then 0\n end as sodium_score\n\n , case\n when bicarbonate_max is null then null\n when bicarbonate_min < 5.0 then 4\n when bicarbonate_max >= 40.0 then 3\n when bicarbonate_min < 10.0 then 3\n when bicarbonate_max >= 30.0 then 1\n when bicarbonate_min < 20.0 then 1\n when bicarbonate_max >= 20.0 and bicarbonate_max < 30.0\n and bicarbonate_min >= 20.0 and bicarbonate_min < 30.0\n then 0\n end as bicarbonate_score\n\n , case\n when mingcs is null then null\n when mingcs < 3 then null
-- erroneous value/on trach\n when mingcs = 3 then 4\n when mingcs < 7 then 3\n when mingcs < 10 then 2\n when mingcs < 13 then 1\n when mingcs >= 13\n and mingcs <= 15\n then 0\n end as gcs_score\nfrom cohort\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n-- coalesce statements impute normal score of zero if data element is missing\n, coalesce(age_score,0)\n+ coalesce(hr_score,0)\n+ coalesce(sysbp_score,0)\n+ coalesce(resp_score,0)\n+ coalesce(temp_score,0)\n+ coalesce(uo_score,0)\n+ coalesce(vent_score,0)\n+ coalesce(bun_score,0)\n+ coalesce(hematocrit_score,0)\n+ coalesce(wbc_score,0)\n+ coalesce(glucose_score,0)\n+ coalesce(potassium_score,0)\n+ coalesce(sodium_score,0)\n+ coalesce(bicarbonate_score,0)\n+ coalesce(gcs_score,0)\n as saps\n, age_score\n, hr_score\n, sysbp_score\n, resp_score\n, temp_score\n, uo_score\n, vent_score\n, bun_score\n, hematocrit_score\n, wbc_score\n, glucose_score\n, potassium_score\n, sodium_score\n, bicarbonate_score\n, gcs_score\n\nFROM icustays ie\nleft join scorecomp s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n-- jing add tail\nalter table mimic3.severityscores_saps\nowner to postgres;"
sapsii <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_sapsii;\ncreate materialized view mimic3.severityscores_sapsii\ntablespace pg_default\nas\n-- jing add head\n-- ------------------------------------------------------------------\n-- Title: Simplified Acute Physiology Score II (SAPS II)\n-- This query extracts the simplified acute physiology score II.\n-- This score is a measure of patient severity of illness.\n-- The score is calculated on the first day of each ICU patients' stay.\n-- ------------------------------------------------------------------\n\n-- Reference for severityscores_saps II:\n-- Le Gall, Jean-Roger, Stanley Lemeshow, and Fabienne Saulnier.\n-- \"A new simplified acute physiology score (SAPS II) based on a European/North American multicenter study.\"\n-- JAMA 270, no. 24 (1993): 2957-2963.\n\n-- Variables used in severityscores_saps II:\n-- Age, gcs\n-- VITALS: Heart rate, systolic blood pressure, temperature\n-- FLAGS: ventilation/cpap\n-- IO: urine output\n-- LABS: PaO2/FiO2 ratio, blood urea nitrogen, wbc, potassium, sodium, hco3\n\n-- The following views are required to run this query:\n-- 1) firstday_urine_output - generated by urine-output-first-day.sql\n-- 2) durations_ventilation_durations - generated by durations_ventilation_durations.sql\n-- 3) firstday_vitals - generated by vitals-first-day.sql\n-- 4) firstday_gcs - generated by gcs-first-day.sql\n-- 5) firstday_labs - generated by labs-first-day.sql\n-- 6) blood_gas_arterial_first_day - generated by blood-gas-first-day-arterial.sql\n\n-- Note:\n-- The score is calculated for *all* ICU patients, with the assumption that the user will subselect appropriate ICUSTAY_IDs.\n-- For example, the score is calculated for neonates, but it is likely inappropriate to actually use the score values for these patients.\n\n-- extract CPAP from the \"Oxygen Delivery Device\" fields\nwith cpap as\n(\n select ie.icustay_id\n , min(DATETIME_SUB(charttime, INTERVAL '1' HOUR)) as starttime\n , max(DATETIME_ADD(charttime, INTERVAL '4' HOUR)) as endtime\n , max(CASE\n WHEN lower(ce.value) LIKE '%cpap%' THEN 1\n WHEN lower(ce.value) LIKE '%bipap mask%' THEN 1\n else 0 end) as cpap\n FROM icustays ie\n inner join chartevents ce\n on ie.icustay_id = ce.icustay_id\n and ce.charttime between ie.intime and DATETIME_ADD(ie.intime, INTERVAL '1' DAY)\n where itemid in\n (\n -- TODO: when metavision data import fixed, check the values in 226732 match the value clause below\n 467, 469, 226732\n )\n and (lower(ce.value) LIKE '%cpap%' or lower(ce.value) LIKE '%bipap mask%')\n -- exclude rows marked as error\n AND (ce.error IS NULL OR ce.error = 0)\n group by ie.icustay_id\n)\n-- extract a flag for surgical service\n-- this combined with \"elective\" FROM admissions table defines elective/non-elective surgery\n, surgflag as\n(\n select adm.hadm_id\n , case when lower(curr_service) like '%surg%' then 1 else 0 end as surgical\n , ROW_NUMBER() over\n (\n PARTITION BY adm.HADM_ID\n ORDER BY TRANSFERTIME\n ) as serviceOrder\n FROM admissions adm\n left join services se\n on adm.hadm_id = se.hadm_id\n)\n-- icd-9 diagnostic codes are our best source for comorbidity information\n-- unfortunately, they are technically a-causal\n-- however, this shouldn't matter too much for the severityscores_saps II comorbidities\n, comorb as\n(\nselect hadm_id\n-- these are slightly different than elixhauser comorbidities, but based on them\n
-- they include some non-comorbid ICD-9 codes (e.g. 20302, relapse of multiple myeloma)\n , max(CASE\n when SUBSTR(icd9_code,1,3) BETWEEN '042' AND '044' THEN 1\n end) as aids /* HIV and AIDS */\n , max(CASE\n when icd9_code between '20000' and '20238' then 1 -- lymphoma\n when icd9_code between '20240' and '20248' then 1 -- leukemia\n when icd9_code between '20250' and '20302' then 1 -- lymphoma\n when icd9_code between '20310' and '20312' then 1 -- leukemia\n when icd9_code between '20302' and '20382' then 1 -- lymphoma\n when icd9_code between '20400' and '20522' then 1 -- chronic leukemia\n when icd9_code between '20580' and '20702' then 1 -- other myeloid leukemia\n when icd9_code between '20720' and '20892' then 1 -- other myeloid leukemia\n when SUBSTR(icd9_code,1,4) = '2386' then 1 -- lymphoma\n when SUBSTR(icd9_code,1,4) = '2733' then 1 -- lymphoma\n end) as hem\n , max(CASE\n when SUBSTR(icd9_code,1,4) BETWEEN '1960' AND '1991' THEN 1\n when icd9_code between '20970' and '20975' then 1\n when icd9_code = '20979' then 1\n when icd9_code = '78951' then 1\n end) as mets /* Metastatic cancer */\n from diagnoses_icd\n group by hadm_id\n)\n, pafi1 as\n(\n -- join blood gas to ventilation durations to determine if patient was vent\n -- also join to cpap table for the same purpose\n select bg.icustay_id, bg.charttime\n , pao2fio2\n , case when vd.icustay_id is not null then 1 else 0 end as vent\n , case when cp.icustay_id is not null then 1 else 0 end as cpap\n from firstday_blood_gas_arterial bg\n left join durations_ventilation_durations vd\n on bg.icustay_id = vd.icustay_id\n and bg.charttime >= vd.starttime\n and bg.charttime <= vd.endtime\n left join cpap cp\n on bg.icustay_id = cp.icustay_id\n and bg.charttime >= cp.starttime\n and bg.charttime <= cp.endtime\n)\n, pafi2 as\n(\n -- get the minimum PaO2/FiO2 ratio *only for ventilated/cpap patients*\n select icustay_id\n , min(pao2fio2) as pao2fio2_vent_min\n from pafi1\n where vent = 1 or cpap = 1\n group by icustay_id\n)\n, cohort as\n(\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n , ie.intime\n , ie.outtime\n\n -- the casts ensure the result is numeric.. we could equally extract EPOCH from the interval\n -- however this code works in Oracle and Postgres\n , datetime_diff(ie.intime, pat.dob,'YEAR') as age\n\n , vital.heartrate_max\n , vital.heartrate_min\n , vital.sysbp_max\n , vital.sysbp_min\n , vital.tempc_max\n , vital.tempc_min\n\n -- this value is non-null iff the patient is on vent/cpap\n , pf.pao2fio2_vent_min\n\n , uo.urineoutput\n\n , labs.bun_min\n , labs.bun_max\n , labs.wbc_min\n , labs.wbc_max\n , labs.potassium_min\n , labs.potassium_max\n , labs.sodium_min\n , labs.sodium_max\n , labs.bicarbonate_min\n , labs.bicarbonate_max\n , labs.bilirubin_min\n , labs.bilirubin_max\n\n , gcs.mingcs\n\n , comorb.aids\n , comorb.hem\n , comorb.mets\n\n , case\n when adm.ADMISSION_TYPE = 'ELECTIVE' and sf.surgical = 1\n then 'ScheduledSurgical'\n when adm.ADMISSION_TYPE != 'ELECTIVE' and sf.surgical = 1\n then 'UnscheduledSurgical'\n else 'Medical'\n end as admissiontype\n\n\nFROM icustays ie\ninner join admissions adm\n on ie.hadm_id = adm.hadm_id\ninner join patients pat\n on ie.subject_id = pat.subject_id\n\n
-- join to above views\nleft join pafi2 pf\n on ie.icustay_id = pf.icustay_id\nleft join surgflag sf\n on adm.hadm_id = sf.hadm_id and sf.serviceOrder = 1\nleft join comorb\n on ie.hadm_id = comorb.hadm_id\n\n-- join to custom tables to get more data....\nleft join firstday_gcs gcs\n on ie.icustay_id = gcs.icustay_id\nleft join firstday_vitals vital\n on ie.icustay_id = vital.icustay_id\nleft join firstday_urine_output uo\n on ie.icustay_id = uo.icustay_id\nleft join firstday_labs labs\n on ie.icustay_id = labs.icustay_id\n)\n, scorecomp as\n(\nselect\n cohort.*\n -- Below code calculates the component scores needed for severityscores_saps\n , case\n when age is null then null\n when age < 40 then 0\n when age < 60 then 7\n when age < 70 then 12\n when age < 75 then 15\n when age < 80 then 16\n when age >= 80 then 18\n end as age_score\n\n , case\n when heartrate_max is null then null\n when heartrate_min < 40 then 11\n when heartrate_max >= 160 then 7\n when heartrate_max >= 120 then 4\n when heartrate_min < 70 then 2\n when heartrate_max >= 70 and heartrate_max < 120\n and heartrate_min >= 70 and heartrate_min < 120\n then 0\n end as hr_score\n\n , case\n when sysbp_min is null then null\n when sysbp_min < 70 then 13\n when sysbp_min < 100 then 5\n when sysbp_max >= 200 then 2\n when sysbp_max >= 100 and sysbp_max < 200\n and sysbp_min >= 100 and sysbp_min < 200\n then 0\n end as sysbp_score\n\n , case\n when tempc_max is null then null\n when tempc_min < 39.0 then 0\n when tempc_max >= 39.0 then 3\n end as temp_score\n\n , case\n when pao2fio2_vent_min is null then null\n when pao2fio2_vent_min < 100 then 11\n when pao2fio2_vent_min < 200 then 9\n when pao2fio2_vent_min >= 200 then 6\n end as pao2fio2_score\n\n , case\n when urineoutput is null then null\n when urineoutput < 500.0 then 11\n when urineoutput < 1000.0 then 4\n when urineoutput >= 1000.0 then 0\n end as uo_score\n\n , case\n when bun_max is null then null\n when bun_max < 28.0 then 0\n when bun_max < 84.0 then 6\n when bun_max >= 84.0 then 10\n end as bun_score\n\n , case\n when wbc_max is null then null\n when wbc_min < 1.0 then 12\n when wbc_max >= 20.0 then 3\n when wbc_max >= 1.0 and wbc_max < 20.0\n and wbc_min >= 1.0 and wbc_min < 20.0\n then 0\n end as wbc_score\n\n , case\n when potassium_max is null then null\n when potassium_min < 3.0 then 3\n when potassium_max >= 5.0 then 3\n when potassium_max >= 3.0 and potassium_max < 5.0\n and potassium_min >= 3.0 and potassium_min < 5.0\n then 0\n end as potassium_score\n\n , case\n when sodium_max is null then null\n when sodium_min < 125 then 5\n when sodium_max >= 145 then 1\n when sodium_max >= 125 and sodium_max < 145\n and sodium_min >= 125 and sodium_min < 145\n then 0\n end as sodium_score\n\n ,
case\n when bicarbonate_max is null then null\n when bicarbonate_min < 15.0 then 5\n when bicarbonate_min < 20.0 then 3\n when bicarbonate_max >= 20.0\n and bicarbonate_min >= 20.0\n then 0\n end as bicarbonate_score\n\n , case\n when bilirubin_max is null then null\n when bilirubin_max < 4.0 then 0\n when bilirubin_max < 6.0 then 4\n when bilirubin_max >= 6.0 then 9\n end as bilirubin_score\n\n , case\n when mingcs is null then null\n when mingcs < 3 then null -- erroneous value/on trach\n when mingcs < 6 then 26\n when mingcs < 9 then 13\n when mingcs < 11 then 7\n when mingcs < 14 then 5\n when mingcs >= 14\n and mingcs <= 15\n then 0\n end as gcs_score\n\n , case\n when aids = 1 then 17\n when hem = 1 then 10\n when mets = 1 then 9\n else 0\n end as comorbidity_score\n\n , case\n when admissiontype = 'ScheduledSurgical' then 0\n when admissiontype = 'Medical' then 6\n when admissiontype = 'UnscheduledSurgical' then 8\n else null\n end as admissiontype_score\n\nfrom cohort\n)\n-- Calculate severityscores_saps II here so we can use it in the probability calculation below\n, score as\n(\n select s.*\n -- coalesce statements impute normal score of zero if data element is missing\n , coalesce(age_score,0)\n + coalesce(hr_score,0)\n + coalesce(sysbp_score,0)\n + coalesce(temp_score,0)\n + coalesce(pao2fio2_score,0)\n + coalesce(uo_score,0)\n + coalesce(bun_score,0)\n + coalesce(wbc_score,0)\n + coalesce(potassium_score,0)\n + coalesce(sodium_score,0)\n + coalesce(bicarbonate_score,0)\n + coalesce(bilirubin_score,0)\n + coalesce(gcs_score,0)\n + coalesce(comorbidity_score,0)\n + coalesce(admissiontype_score,0)\n as sapsii\n from scorecomp s\n)\nselect ie.subject_id, ie.hadm_id, ie.icustay_id\n, sapsii\n, 1 / (1 + exp(- (-7.7631 + 0.0737*(sapsii) + 0.9971*(ln(sapsii + 1))) )) as sapsii_prob\n, age_score\n, hr_score\n, sysbp_score\n, temp_score\n, pao2fio2_score\n, uo_score\n, bun_score\n, wbc_score\n, potassium_score\n, sodium_score\n, bicarbonate_score\n, bilirubin_score\n, gcs_score\n, comorbidity_score\n, admissiontype_score\nFROM icustays ie\nleft join score s\n on ie.icustay_id = s.icustay_id\norder by ie.icustay_id;\n
--- jing add tail\nalter table mimic3.severityscores_sapsii\nowner to postgres;"
sirs <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_sirs;\nCREATE MATERIALIZED VIEW mimic3.severityscores_sirs\nTABLESPACE pg_default\nAS\n WITH bg AS (\n SELECT bg.icustay_id,\n min(bg.pco2) AS paco2_min\n FROM mimic3.firstday_blood_gas_arterial bg\n WHERE bg.specimen_pred = 'ART'::text\n GROUP BY bg.icustay_id\n ), scorecomp AS (\n SELECT ie_1.icustay_id,\n v.tempc_min,\n v.tempc_max,\n v.heartrate_max,\n v.resprate_max,\n bg.paco2_min,\n l.wbc_min,\n l.wbc_max,\n l.bands_max\n FROM mimic3.icustays ie_1\n LEFT JOIN bg ON ie_1.icustay_id = bg.icustay_id\n LEFT JOIN mimic3.firstday_vitals v ON ie_1.icustay_id = v.icustay_id\n LEFT JOIN mimic3.firstday_labs l ON ie_1.icustay_id = l.icustay_id\n ), scorecalc AS (\n SELECT scorecomp.icustay_id,\n CASE\n WHEN scorecomp.tempc_min < 36.0::double precision THEN 1\n WHEN scorecomp.tempc_max > 38.0::double precision THEN 1\n WHEN scorecomp.tempc_min IS NULL THEN NULL::integer\n ELSE 0\n END AS temp_score,\n CASE\n WHEN scorecomp.heartrate_max > 90.0::double precision THEN 1\n WHEN scorecomp.heartrate_max IS NULL THEN NULL::integer\n ELSE 0\n END AS heartrate_score,\n CASE\n WHEN scorecomp.resprate_max > 20.0::double precision THEN 1\n WHEN scorecomp.paco2_min < 32.0::double precision THEN 1\n WHEN COALESCE(scorecomp.resprate_max, scorecomp.paco2_min) IS NULL THEN NULL::integer\n ELSE 0\n END AS resp_score,\n CASE\n WHEN scorecomp.wbc_min < 4.0::double precision THEN 1\n WHEN scorecomp.wbc_max > 12.0::double precision THEN 1\n WHEN scorecomp.bands_max > 10::double precision THEN 1\n WHEN COALESCE(scorecomp.wbc_min, scorecomp.bands_max) IS NULL THEN NULL::integer\n ELSE 0\n END AS wbc_score\n FROM scorecomp\n )\n SELECT ie.subject_id,\n ie.hadm_id,\n ie.icustay_id,\n COALESCE(s.temp_score, 0) + COALESCE(s.heartrate_score, 0) + COALESCE(s.resp_score, 0) + COALESCE(s.wbc_score, 0) AS sirs,\n s.temp_score,\n s.heartrate_score,\n s.resp_score,\n s.wbc_score\n FROM mimic3.icustays ie\n LEFT JOIN scorecalc s ON ie.icustay_id = s.icustay_id\n ORDER BY ie.icustay_id\nWITH DATA;\n\nALTER TABLE mimic3.severityscores_sirs\n OWNER TO postgres;"
sofa <- "SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS severityscores_sofa;\nCREATE MATERIALIZED VIEW mimic3.severityscores_sofa\nTABLESPACE pg_default\nAS\n WITH wt AS (\n SELECT ie_1.icustay_id,\n avg(\n CASE\n WHEN c.itemid = ANY (ARRAY[762, 763, 3723, 3580, 226512]) THEN c.valuenum\n WHEN c.itemid = 3581 THEN c.valuenum * 0.45359237::double precision\n WHEN c.itemid = 3582 THEN c.valuenum * 0.0283495231::double precision\n ELSE NULL::double precision\n END) AS weight\n FROM mimic3.icustays ie_1\n LEFT JOIN mimic3.chartevents c ON ie_1.icustay_id = c.icustay_id\n WHERE c.valuenum IS NOT NULL AND (c.itemid = ANY (ARRAY[762, 763, 3723, 3580, 3581, 3582, 226512])) AND c.valuenum <> 0::double precision AND c.charttime >= mimic3.datetime_sub(ie_1.intime, '1 day'::interval day) AND c.charttime <= mimic3.datetime_add(ie_1.intime, '1 day'::interval day) AND (c.error IS NULL OR c.error = 0)\n GROUP BY ie_1.icustay_id\n ), echo2 AS (\n SELECT ie_1.icustay_id,\n avg(echo.weight * 0.45359237) AS weight\n FROM mimic3.icustays ie_1\n LEFT JOIN mimic3.echo_data echo ON ie_1.hadm_id = echo.hadm_id AND echo.charttime > mimic3.datetime_sub(ie_1.intime, '7 days'::interval day) AND echo.charttime < mimic3.datetime_add(ie_1.intime, '1 day'::interval day)\n GROUP BY ie_1.icustay_id\n ), vaso_cv AS (\n SELECT ie_1.icustay_id,\n max(\n CASE\n WHEN cv.itemid = 30047 THEN cv.rate / COALESCE(wt.weight, ec.weight::double precision)\n WHEN cv.itemid = 30120 THEN cv.rate\n ELSE NULL::double precision\n END) AS rate_norepinephrine,\n max(\n CASE\n WHEN cv.itemid = 30044 THEN cv.rate / COALESCE(wt.weight, ec.weight::double precision)\n WHEN cv.itemid = ANY (ARRAY[30119, 30309]) THEN cv.rate\n ELSE NULL::double precision\n END) AS rate_epinephrine,\n max(\n
CASE\n WHEN cv.itemid = ANY (ARRAY[30043, 30307]) THEN cv.rate\n ELSE NULL::double precision\n END) AS rate_dopamine,\n max(\n CASE\n WHEN cv.itemid = ANY (ARRAY[30042, 30306]) THEN cv.rate\n ELSE NULL::double precision\n END) AS rate_dobutamine\n FROM mimic3.icustays ie_1\n JOIN mimic3.inputevents_cv cv ON ie_1.icustay_id = cv.icustay_id AND cv.charttime >= ie_1.intime AND cv.charttime <= mimic3.datetime_add(ie_1.intime, '1 day'::interval day)\n LEFT JOIN wt ON ie_1.icustay_id = wt.icustay_id\n LEFT JOIN echo2 ec ON ie_1.icustay_id = ec.icustay_id\n WHERE (cv.itemid = ANY (ARRAY[30047, 30120, 30044, 30119, 30309, 30043, 30307, 30042, 30306])) AND cv.rate IS NOT NULL\n GROUP BY ie_1.icustay_id\n ), vaso_mv AS (\n SELECT ie_1.icustay_id,\n max(\n CASE\n WHEN mv.itemid = 221906 THEN mv.rate\n ELSE NULL::double precision\n END) AS rate_norepinephrine,\n max(\n CASE\n WHEN mv.itemid = 221289 THEN mv.rate\n ELSE NULL::double precision\n END) AS rate_epinephrine,\n max(\n CASE\n WHEN mv.itemid = 221662 THEN mv.rate\n ELSE NULL::double precision\n END) AS rate_dopamine,\n max(\n CASE\n WHEN mv.itemid = 221653 THEN mv.rate\n ELSE NULL::double precision\n END) AS rate_dobutamine\n FROM mimic3.icustays ie_1\n JOIN mimic3.inputevents_mv mv ON ie_1.icustay_id = mv.icustay_id AND mv.starttime >= ie_1.intime AND mv.starttime <= mimic3.datetime_add(ie_1.intime, '1 day'::interval day)\n WHERE (mv.itemid = ANY (ARRAY[221906, 221289, 221662, 221653])) AND mv.statusdescription::text <> 'Rewritten'::text\n GROUP BY ie_1.icustay_id\n ), pafi1 AS (\n SELECT bg.icustay_id,\n bg.charttime,\n bg.pao2fio2,\n CASE\n WHEN vd.icustay_id IS NOT NULL THEN 1\n ELSE 0\n END AS isvent\n FROM mimic3.firstday_blood_gas_arterial bg\n LEFT JOIN mimic3.durations_ventilation_durations vd ON bg.icustay_id = vd.icustay_id AND bg.charttime >= vd.starttime AND bg.charttime <= vd.endtime\n ORDER BY bg.icustay_id, bg.charttime\n ), pafi2 AS (\n SELECT pafi1.icustay_id,\n min(\n CASE\n WHEN pafi1.isvent = 0 THEN pafi1.pao2fio2\n ELSE NULL::double precision\n END) AS pao2fio2_novent_min,\n min(\n
CASE\n WHEN pafi1.isvent = 1 THEN pafi1.pao2fio2\n ELSE NULL::double precision\n END) AS pao2fio2_vent_min\n FROM pafi1\n GROUP BY pafi1.icustay_id\n ), scorecomp AS (\n SELECT ie_1.icustay_id,\n v.meanbp_min,\n COALESCE(cv.rate_norepinephrine, mv.rate_norepinephrine) AS rate_norepinephrine,\n COALESCE(cv.rate_epinephrine, mv.rate_epinephrine) AS rate_epinephrine,\n COALESCE(cv.rate_dopamine, mv.rate_dopamine) AS rate_dopamine,\n COALESCE(cv.rate_dobutamine, mv.rate_dobutamine) AS rate_dobutamine,\n l.creatinine_max,\n l.bilirubin_max,\n l.platelet_min,\n pf.pao2fio2_novent_min,\n pf.pao2fio2_vent_min,\n uo.urineoutput,\n gcs.mingcs\n FROM mimic3.icustays ie_1\n LEFT JOIN vaso_cv cv ON ie_1.icustay_id = cv.icustay_id\n LEFT JOIN vaso_mv mv ON ie_1.icustay_id = mv.icustay_id\n LEFT JOIN pafi2 pf ON ie_1.icustay_id = pf.icustay_id\n LEFT JOIN mimic3.firstday_vitals v ON ie_1.icustay_id = v.icustay_id\n LEFT JOIN mimic3.firstday_labs l ON ie_1.icustay_id = l.icustay_id\n LEFT JOIN mimic3.firstday_urine_output uo ON ie_1.icustay_id = uo.icustay_id\n LEFT JOIN mimic3.firstday_gcs gcs ON ie_1.icustay_id = gcs.icustay_id\n ), scorecalc AS (\n SELECT scorecomp.icustay_id,\n CASE\n WHEN scorecomp.pao2fio2_vent_min < 100::double precision THEN 4\n WHEN scorecomp.pao2fio2_vent_min < 200::double precision THEN 3\n WHEN scorecomp.pao2fio2_novent_min < 300::double precision THEN 2\n WHEN scorecomp.pao2fio2_novent_min < 400::double precision THEN 1\n WHEN COALESCE(scorecomp.pao2fio2_vent_min, scorecomp.pao2fio2_novent_min) IS NULL THEN NULL::integer\n ELSE 0\n END AS respiration,\n CASE\n WHEN scorecomp.platelet_min < 20::double precision THEN 4\n WHEN scorecomp.platelet_min < 50::double precision THEN 3\n WHEN scorecomp.platelet_min < 100::double precision THEN 2\n WHEN scorecomp.platelet_min < 150::double precision THEN 1\n WHEN scorecomp.platelet_min IS NULL THEN NULL::integer\n ELSE 0\n END AS coagulation,\n CASE\n WHEN scorecomp.bilirubin_max >= 12.0::double precision THEN 4\n WHEN scorecomp.bilirubin_max >= 6.0::double precision THEN 3\n WHEN scorecomp.bilirubin_max >= 2.0::double precision THEN 2\n WHEN scorecomp.bilirubin_max >= 1.2::double precision THEN 1\n WHEN scorecomp.bilirubin_max IS NULL THEN NULL::integer\n ELSE 0\n END AS liver,\n
CASE\n WHEN scorecomp.rate_dopamine > 15::double precision OR scorecomp.rate_epinephrine > 0.1::double precision OR scorecomp.rate_norepinephrine > 0.1::double precision THEN 4\n WHEN scorecomp.rate_dopamine > 5::double precision OR scorecomp.rate_epinephrine <= 0.1::double precision OR scorecomp.rate_norepinephrine <= 0.1::double precision THEN 3\n WHEN scorecomp.rate_dopamine > 0::double precision OR scorecomp.rate_dobutamine > 0::double precision THEN 2\n WHEN scorecomp.meanbp_min < 70::double precision THEN 1\n WHEN COALESCE(scorecomp.meanbp_min, scorecomp.rate_dopamine, scorecomp.rate_dobutamine, scorecomp.rate_epinephrine, scorecomp.rate_norepinephrine) IS NULL THEN NULL::integer\n ELSE 0\n END AS cardiovascular,\n CASE\n WHEN scorecomp.mingcs >= 13::double precision AND scorecomp.mingcs <= 14::double precision THEN 1\n WHEN scorecomp.mingcs >= 10::double precision AND scorecomp.mingcs <= 12::double precision THEN 2\n WHEN scorecomp.mingcs >= 6::double precision AND scorecomp.mingcs <= 9::double precision THEN 3\n WHEN scorecomp.mingcs < 6::double precision THEN 4\n WHEN scorecomp.mingcs IS NULL THEN NULL::integer\n ELSE 0\n END AS cns,\n CASE\n WHEN scorecomp.creatinine_max >= 5.0::double precision THEN 4\n WHEN scorecomp.urineoutput < 200::double precision THEN 4\n WHEN scorecomp.creatinine_max >= 3.5::double precision AND scorecomp.creatinine_max < 5.0::double precision THEN 3\n WHEN scorecomp.urineoutput < 500::double precision THEN 3\n WHEN scorecomp.creatinine_max >= 2.0::double precision AND scorecomp.creatinine_max < 3.5::double precision THEN 2\n WHEN scorecomp.creatinine_max >= 1.2::double precision AND scorecomp.creatinine_max < 2.0::double precision THEN 1\n WHEN COALESCE(scorecomp.urineoutput, scorecomp.creatinine_max) IS NULL THEN NULL::integer\n ELSE 0\n END AS renal\n FROM scorecomp\n )\n SELECT ie.subject_id,\n ie.hadm_id,\n ie.icustay_id,\n COALESCE(s.respiration, 0) + COALESCE(s.coagulation, 0) + COALESCE(s.liver, 0) + COALESCE(s.cardiovascular, 0) + COALESCE(s.cns, 0) + COALESCE(s.renal, 0) AS sofa,\n s.respiration,\n s.coagulation,\n s.liver,\n s.cardiovascular,\n s.cns,\n s.renal\n FROM mimic3.icustays ie\n LEFT JOIN scorecalc s ON ie.icustay_id = s.icustay_id\n ORDER BY ie.icustay_id\nWITH DATA;\n\nALTER TABLE mimic3.severityscores_sofa\n OWNER TO postgres;"
dirnames <- c("top level data", "top level data", "durations", "durations",
"durations", "durations", "durations", "durations", "durations",
"durations", "durations", "durations", "durations", "durations",
"durations", "durations", "durations", "durations", "durations",
"durations", "durations", "durations", "durations", "durations",
"durations", "comorbidity", "comorbidity", "comorbidity", "comorbidity",
"comorbidity", "cookbooks", "cookbooks", "cookbooks", "cookbooks",
"cookbooks", "cookbooks", "cookbooks", "cookbooks", "cookbooks",
"cookbooks", "cookbooks", "cookbooks", "cookbooks", "cookbooks",
"cookbooks", "cookbooks", "cookbooks", "cookbooks", "cookbooks",
"cookbooks", "cookbooks", "cookbooks", "cookbooks", "cookbooks",
"demographics", "demographics", "demographics", "demographics",
"demographics", "firstday", "firstday", "firstday", "firstday",
"firstday", "firstday", "firstday", "firstday", "firstday", "firstday",
"fluid_balance", "fluid_balance", "fluid_balance", "fluid_balance",
"fluid_balance", "sepsis", "sepsis", "sepsis", "diagnosis", "diagnosis",
"organfailure", "organfailure", "organfailure", "organfailure",
"organfailure", "organfailure", "severityscores", "severityscores",
"severityscores", "severityscores", "severityscores", "severityscores",
"severityscores", "severityscores", "severityscores")
tablenames <- c("code_status", "echo_data", "ventilation_classification", "ventilation_durations",
"crrt_durations", "adenosine_durations", "dobutamine_durations",
"dopamine_durations", "epinephrine_durations", "isuprel_durations",
"milrinone_durations", "norepinephrine_durations", "phenylephrine_durations",
"vasopressin_durations", "vasopressor_durations", "weight_durations",
"arterial_line_durations", "central_line_durations", "dobutamine_dose",
"dopamine_dose", "epinephrine_dose", "norepinephrine_dose", "neuroblock_dose",
"vasopressin_dose", "phenylephrine_dose", "elixhauser_ahrq_v37",
"elixhauser_ahrq_v37_no_drg", "elixhauser_quan", "elixhauser_score_ahrq",
"elixhauser_score_quan", "age_histogram", "basic_patient_info",
"bun", "gcs", "glucose", "hco", "heart_rate", "height", "icd9agelimited",
"icd9count", "icd9vagehistogram", "icd9vicd9agelimited", "icd9vicd9count",
"icustay_days", "min_surviving_bp", "mortality", "number_of_patients",
"potassium", "rr", "sbp", "sodium", "temp", "uo", "wbc", "heightweight",
"icustay_detail", "icustay_times", "icustay_hours", "note_counts",
"blood_gas_first_day", "blood_gas_first_day_arterial", "gcs_first_day",
"height_first_day", "labs_first_day", "rrt_first_day", "urine_output_first_day",
"ventilation_first_day", "vitals_first_day", "weight_first_day",
"colloid_bolus", "crystalloid_bolus", "ffp_transfusion", "rbc_transfusion",
"urine_output", "angus", "explicit", "martin", "ccs_diagnosis_table_psql",
"ccs_dx", "kdigo_creatinine", "kdigo_uo", "kdigo_stages", "kdigo_stages_48hr",
"kdigo_stages_7day", "meld", "apsiii", "lods", "mlods", "oasis",
"qsofa", "saps", "sapsii", "sirs", "sofa")
x=c(code_status, echo_data, ventilation_classification, ventilation_durations, crrt_durations, adenosine_durations, dobutamine_durations, dopamine_durations, epinephrine_durations, isuprel_durations, milrinone_durations, norepinephrine_durations, phenylephrine_durations, vasopressin_durations, vasopressor_durations, weight_durations, arterial_line_durations, central_line_durations, dobutamine_dose, dopamine_dose, epinephrine_dose, norepinephrine_dose, neuroblock_dose, vasopressin_dose, phenylephrine_dose, elixhauser_ahrq_v37, elixhauser_ahrq_v37_no_drg, elixhauser_quan, elixhauser_score_ahrq, elixhauser_score_quan, age_histogram, basic_patient_info, bun, gcs, glucose, hco, heart_rate, height, icd9agelimited, icd9count, icd9vagehistogram, icd9vicd9agelimited, icd9vicd9count, icustay_days, min_surviving_bp, mortality, number_of_patients, potassium, rr, sbp, sodium, temp, uo, wbc, heightweight, icustay_detail, icustay_times, icustay_hours, note_counts, blood_gas_first_day, blood_gas_first_day_arterial, gcs_first_day, height_first_day, labs_first_day, rrt_first_day, urine_output_first_day, ventilation_first_day, vitals_first_day, weight_first_day, colloid_bolus, crystalloid_bolus, ffp_transfusion, rbc_transfusion, urine_output, angus, explicit, martin, ccs_diagnosis_table_psql, ccs_dx, kdigo_creatinine, kdigo_uo, kdigo_stages, kdigo_stages_48hr, kdigo_stages_7day, meld, apsiii, lods, mlods, oasis, qsofa, saps, sapsii, sirs, sofa)
if (missing(conn)) conn=get('connect_MIMIC',envir = .GlobalEnv)
for (i in 1:94) {
if (i==1){
cat('\n')
message(dirnames[i],' ',sum(dirnames==dirnames[i]))
starttime = Sys.time()
t = Sys.time()
}
cat(paste0(i,'.'),tablenames[i],
do::rep_n(' ',max(nchar(tablenames))-nchar(tablenames[i]) + 3+2-nchar(i)))
consume = system.time(DBI::dbGetQuery(conn = conn$con,statement =x[i]))
if (tablenames[i] == 'ccs_diagnosis_table_psql'){
DBI::dbGetQuery(conn = conn$con,
statement ="SET client_min_messages TO WARNING;\nset search_path to mimic3;\nDROP MATERIALIZED VIEW IF EXISTS mimic3.diagnosis_ccs_diagnosis_table_sql;\ncreate materialized view mimic3.diagnosis_ccs_diagnosis_table_sql\ntablespace pg_default\nas\nselect * from mimic3.zzz;\nalter table mimic3.diagnosis_ccs_diagnosis_table_sql\nowner to postgres;")
}
cat(time_segment(consume[3]),'\n')
if (i < length(x)){
if (dirnames[i] != dirnames[i+1]){
cat(crayon::blue(paste('This part time:',time_segment(as.numeric(Sys.time())-as.numeric(t)),'\n')))
cat('\n')
message(dirnames[i],' ',sum(dirnames==dirnames[i]))
t = Sys.time()
}
}
if (i == length(x)){
if (dirnames[i] == dirnames[i-1]) cat(crayon::blue(paste('This part time:',time_segment(as.numeric(Sys.time())-as.numeric(t)),'\n')))
cat('Total time:',time_segment(as.numeric(Sys.time())-as.numeric(starttime)),'\n')
}
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.