Table has schema of TIMESTAMP, PATIENTID, ECGVALUE and sample table is given below:
01.34 ANON 12
02.34 ANON 12
03.34 ANON 12
04.34 ANON 12
05.34 ANON 12
06.34 ANON 12
07.34 ANON 12
08.34 ANON 12
10.34 ANON 12
11.34 ANON 12
12.34 ANON 12
Now, I want to select rows which are ‘n’ less or equal than maximum time stamp. From above table we can see that for PATIENTID = ‘ANON’ maximum TIMESTAMP is 12.34, now, I want such an SQL query that shd be able to select all rows that are ‘n’ less than 12.34 where n can be any number. SO far, I have written this, but it does’t work.
WITH
rownums(TIMESTAMP, ECGVALUE, RN) AS (
SELECT TIMESTAMP, ECGVALUE ROW_NUMBER() OVER() AS RN
FROM EKLUND.DEV_RAWECG WERE PATIENID = 'ANON'
),
maxtime(MAXTM) AS (
SELECT MAX(TIMESTAMP) AS MAXTM FROM rownums
)
SELECT TIMESTAMP, ECGVALUE, RN FROM rownums
WHERE TIMESTAMP >= maxtime.MAXTM - 2;
You can’t reference maxtime.MAXTM in your where clause because you haven’t included maxtime in your FROM clause. Instead, you need to change this
to