A SELECT statement as subquery with two conditions
I'm working on a ECG data that basically has the following schema
Col 1 = TIMESTAMP
Col 2 = PATIENTID
Col 3 = ECGVALUE
Now, I'm trying to write a SQL statement that should be able to select all the rows that satisfy the following condition
Row index >= n and TIMESTAMP of xth row <= TIMESTAMP of nth row + offset
To explaing it further, let say I've following data in my database
1.1 ANON 1.1
1.3 ANON 2.3
3.5 ANON 4.3
5.0 ANON 6.5
6.3 ANON 7.5
7.9 ANON 8
8.6 ANON 9.4
Now, I want to select the data from 3rd row till 3 seconds of data has been collected, which means that my resultset should have
3.5 ANON 2.3 *//3rd row till TIMESTAMP <= 3.5 + 3 <= 6.5*
1.3 ANON 2.3
3.5 ANON 4.3
5.0 ANON 6.5
6.3 ANON 7.5
Last two rows are neglected as difference between 开发者_StackOverflow社区TIMESTAMP of first and last cannont go beyond 3. So If I go back to my condition, which is
Row index >= n and TIMESTAMP of xth row <= TIMESTAMP of nth row + offset
Here,
n: nth row from where data must be selected
x: Any arbitary row in result set
offset: Maximum difference between first and last TIMESTAMP of result set.
I've written a working SQL statement for the above condition, but I think its not that much optimized as I'm new to SQL.
SELECT TIMESTAMP, ECGVALUE
FROM
(
SELECT TIMESTAMP, ECGVALUE, ROW_NUMBER() OVER() AS RN
FROM EKLUND.DEV_RAWECG
)
WHERE RN >= n AND TIMESTAMP <=
(
SELECT TIMESTAMP FROM
(
SELECT TIMESTAMP, ROW_NUMBER() OVER() AS TM
)
WHERE TM = n
) + offset;
The code will look a lot cleaner if you use a common table expression, as follows:
WITH rownums(TIMESTAMP, ECGVALUE, RN) AS (
SELECT TIMESTAMP, ECGVALUE, ROW_NUMBER() OVER(ORDER BY TIMESTAMP) AS RN
FROM EKLUND.DEV_RAWECG
)
SELECT allrows.TIMESTAMP, allrows.ECGVALUE, allrows.RN
FROM rownums allrows
CROSS JOIN rownums rown
WHERE rown.RN = n
AND allrows.RN >= n
AND rown.TIMESTAMP + offset >= allrows.TIMESTAMP;
精彩评论