Home > Back-end >  Select rows from last few minutes
Select rows from last few minutes

Time:07-18

I want to achieve this function to select rows from the last few minutes. (Assuming the latest time is 09:34:00)

SELECT CONVERT(VARCHAR(10),cur_time,108) as CUR_TIME, AVG(CAST(now_price AS FLOAT)) AS now_price 
FROM dbo.ticktest
GROUP BY CUR_TIME
HAVING CUR_TIME >= '09:32:30'

But I want it can automatically find the latest cur_time in my table, so I write this function in this way:

SELECT CONVERT(VARCHAR(10),cur_time,108) as CUR_TIME, AVG(CAST(now_price AS FLOAT)) AS now_price
FROM dbo.ticktest
GROUP BY CUR_TIME
HAVING CUR_TIME >= CONVERT(VARCHAR(10),DATEADD(mi,-1,MAX(cur_time)),108)

which returns data from all the period. So, how can I correct this mistake to make the function run properly.

Thanks

CodePudding user response:

use sub query where you always pick the max time which is actually latest time

HAVING CUR_TIME >= (select max(CUR_TIME) from dbo.ticktest)
  • Related