I want to obtain all rows for which, every interval of 48h in a given period of time, are satisfied the following conditions. Every time all of them are true, I put a flag with
This is a stab at an answer. It really needs more complete data to be taken seriously. Here goes:
SELECT
*, 1 AS flag
FROM
(SELECT
*,
valuenum - LAG(valuenum, 1) OVER(partition by item) AS diff,
intime - LAG(intime, 1) OVER(partition by item) AS time_diff
FROM
lab L
JOIN
icu I
ON
L.id_sub = I.id
WHERE
L.item = 50912
AND
L.charttime < I.intime AND L.charttime > (I.intime - INTERVAL '7 DAY')
) AS select_diff
WHERE
select_diff.diff > 0.3
AND
select_diff.time_diff <interval '48 hours';