sqlsql-serversql-date-functions

How to retrieve data for last 2 hrs from a specific Datetime


I am trying to extract last two hours records from a specific datetime. That means, I need to find out if there's any transaction occurred before 2019-11-20 18:00:00. I have 100 records against which I need to extract 2 hrs prior activities.

Can I know how to formulate a sql query to fetch 2 hrs prior records?

This is how I was trying to formulate my code;

select distinct
    ID,
    START_DTTM,

from table1
where START_DTTM between dateadd(hour,-2,getdate()) and getdate();

I tried this between DATEADD(hour, -2 , CAST('2019-11-20 18:00:00' AS DATETIME)) and CAST('2019-11-20 18:00:00' AS DATETIME). returning only 20.

Also tried this; WHERE START_DTTM > DATEADD(hour, -2 , CAST('2019-11-20 18:00:00' AS DATETIME)). This one returns 200 records.

which one would be best approach.


Solution

  • It is very hard to answer this question because you don't tell us anything about the data model but if you want to get the last two hours of records and you have a column with a timestamp just add a where clause onto the select statement that says

     WHERE datetimecolum > DATEADD(hour, -2 , GETDATE())