问题
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 value 1 for it.
This is what I did so far.
DO
$$
DECLARE
i record;
CHARTTIME TIMESTAMP;
BEGIN
FOR i IN SELECT * FROM schema.lab L
JOIN schema.icu I ON L.ID = I.ID
WHERE L.ITEM = 50912 AND
L.CHARTTIME < I.INTIME AND L.CHARTTIME > (I.INTIME - INTERVAL '7 DAY')
LOOP
CHARTTIME := L.CHARTTIME;
FOREACH CHARTTIME IN ARRAY CHARTTIME + INTERVAL '48 HOUR'
LOOP
IF L.VALUENUM > L.VALUENUM + 0.3 THEN
'1'::INTEGER AS FLAG
END IF;
END LOOP;
END LOOP;
END;
$$
;
I get a syntax error. I do not know if this approach is correct, though.
ERROR: syntax error at or near "'1'"
LINE 16: '1'::INTEGER AS FLAG
^
SQL state: 42601
Character: 442
Here's the code for implementing the tables.
CREATE TABLE SCHEMA.LAB (
ID_SUB INTEGER PRIMARY KEY,
ICU INTEGER NOT NULL,
ITEM INTEGER NOT NULL,
CHARTTIME TIMESTAMP NOT NULL,
VALUENUM DOUBLE PRECISION NOT NULL);
CREATE TABLE SCHEMA.ICU (
ID INTEGER PRIMARY KEY,
INTIME TIMESTAMP NOT NULL,
ID_SUB INTEGER);
Rows of LAB are:
(1,1,50912,2020-07-17 20:48:00,0.7)
(2,2,50829,2020-07-17 20:48:00,1)
(3,3,50912,2020-07-18 20:03:00,1)
(4,4,50912,2020-07-20 17:17:00,3.1)
(1,1,73271,2020-05-17 17:58:00,0.2)
(2,2,50912,2020-07-17 21:41:00,1.7)
Rows of ICU are:
(1,2020-06-17 20:01:00,1)
(2,2020-07-15 00:48:00,2)
(3,2020-07-20 20:01:00,3)
(4,2020-07-21 20:03:00,4)
In order to print what I want, I have to satisfy these conditions:
SCHEMA.LAB L JOIN SCHEMA.ICU I ON LAB.ICU=I.ID
and that L.ITEM = 50912 AND L.CHARTTIME < I.INTIME AND L.CHARTTIME > (I.INTIME - INTERVAL '7 DAY')
.
I am searching for an increase of the valuenum of 0.3 within every interval of 48 hours, starting from 7 days before ICU.INTIME value. So I put a flag = 1 if and only if the next valuenum has an increase of 0.3 within 48h wrt the previous one. Then I go on checking the next valuenum for the next 48 hours interval, until the LAB.charttime < ICU.intime
What I want to print is the following:
LAB.ID_SUB, ICU.ID, LAB.ITEM, LAB.CHARTTIME, LAB.VALUENUM, ICU.INTIME FLAG
3, 3, 50912, 2020-07-18 20:03:00, 1, 2020-07-20 20:01:00 1
4, 4, 50912, 2020-07-20 17:17:00, 3.1, 2020-07-21 20:03:00. 1
回答1:
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';
来源:https://stackoverflow.com/questions/64857296/how-do-i-iterate-a-table-according-to-time-intervals-in-postgres