Find records produced in the last hour

后端 未结 4 2041
忘了有多久
忘了有多久 2021-02-20 00:59

I have a smalldatetime field named myTime recording when the record was created. I need the syntax that selects records created within the last hour.

相关标签:
4条回答
  • 2021-02-20 01:19

    If you want whole hours use the following...

    --This Hour
    SELECT  *
    FROM    Whatever
    WHERE   myTime >= dateadd(hour, datediff(hour, 0, GETDATE()), 0)
    
    --Last Hour
    SELECT  *
    FROM    Whatever
    WHERE   myTime  < dateadd(hour, datediff(hour, 0, GETDATE()), 0) AND  myTime >= dateadd(hour, datediff(hour, 0,  DATEADD(HOUR, -1, GETDATE())), 0)
    
    --Hour before last
    SELECT  *
    FROM    Whatever
    WHERE   myTime < dateadd(hour, datediff(hour, 0,  DATEADD(HOUR, -1, GETDATE())), 0) AND  myTime >= dateadd(hour, datediff(hour, 0, DATEADD(HOUR, -2, GETDATE())), 0)
    
    0 讨论(0)
  • 2021-02-20 01:33

    Use this:

    SELECT * FROM YourTable WHERE YourDateTime >= DATEADD(hh, -1, GETDATE())
    
    0 讨论(0)
  • 2021-02-20 01:37

    Although this WHERE myTime > DATEADD(HOUR, -1, GETDATE()) should have worked for me, for some strange reason the datetime feild in my sql server is configured in a strange way where the above code would return the entire day, not just the hour prior to Now. After some troubleshooting I found that GETDATE() was actually 7 hours ahead of the current time so my query looks like this:

    WHERE myTime BETWEEN DATEADD(HH, 6, GETDATE()) AND DATEADD(HH, 7, GETDATE())
    

    So DATEADD(HH, 7, GETDATE() is now plus 7 hours (which comes out being the current time according to the db). And then subtract an hour to get all rows within that hour block. I thought I should post this just to help anyone having the same issue.

    0 讨论(0)
  • 2021-02-20 01:40

    Use this:

    SELECT  *
    FROM    Whatever
    WHERE   myTime > DATEADD(HOUR, -1, GETDATE())
    
    0 讨论(0)
提交回复
热议问题