I'm trying to compute a rolling average using SQL and I was able to compute said average using the OVER
and ROWS BETWEEN
commands. I obtained a rolling average using the rows between the preceding 1 and following 1 rows, code seen below along with output in figure 1.
How can I modify my SQL query below so that I compute this rolling average using a 6 hour window for the observed row value CHARTTIME (i.e., 3 hours before and 3 hours after). Any help or advice would be greatly appreciated.
sql_query <- "SELECT SUBJECT_ID, HADM_ID, chartevents.ITEMID, VALUE, CHARTTIME, LABEL, AVG(SAFE_CAST(VALUE AS INT)) OVER(
PARTITION BY SUBJECT_ID
ORDER BY CHARTTIME
ROWS BETWEEN 1 PRECEDING and 1 FOLLOWING
) AS MV_AVG
FROM chartevents
INNER JOIN d_items ON chartevents.ITEMID = d_items.ITEMID
WHERE chartevents.ITEMID IN (211,220045)
ORDER BY SUBJECT_ID, CHARTTIME
"