Skip to content
Advertisement

Fetch rows for the last 6 hours in SQL Server

I run a Microsoft SQL Server SELECT query and have an issue trying to define a specific time range for that query every 6 hours (I am a newer user of SQL Server).

I have an external script calling this SQL Server database every 6 hours, so I only need the newly produced data from the previous 6 hours until the current time.

For example, if my script executes at 6:00pm PST, I only need the data between 12:00 P.M.- 6:00 P.M. for that current day (or the previous day if script cron job falls between a day range.

An example of my query is below

SELECT *
FROM        
    (SELECT 
         CONVERT(VARCHAR(30), GETUTCDATE(), 121 AS Current_SYSTEM_TIME,
         Table1.Column_11,
         Table1.Column_12,
         Table1.Column_13,
         Table2.Column_11,
         Table2.Column_12,
         Table2.Column_13,
         Table3.Column_11,
         Table3.Column_12,
         Table3.Column_13
     FROM 
         Table1
     INNER JOIN 
         Table2 ON (Table1.Column_11 = Table2.Column_11)
     INNER JOIN 
         Table3 ON (Table1.Column_11 = Table3.Column_11)
     WHERE 
         Table3.Column_12 'pass') a
WHERE 
    Table3.Column_13 < 2 
     AND Current_SYSTEM_TIME BETWEEN DATEADD(day, -1, GETUTCDATE()) AND GETUTCDATE() 

Advertisement

Answer

Welcome to Community!

Please try below WHERE condition in your query with HOUR(hh) range.

.......
.......
WHERE Table3.Column_13 < 2 AND <event_time> BETWEEN DATEADD(hh, -6, GETUTCDATE()) AND GETUTCDATE() 

EDITED: As per your comment above! Please apply your where condition on <event_time> field!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement