SQL - 在当前日期/时间之后选择记录

时间:2011-07-05 12:05:54

标签: sql time where-clause

所以我有一张下面的表格

Date       Time        Field3        Field4 - etc.
--------------------------------------------------
05/07/11   17:45       blah          blah
05/07/11   19:45       blah          blah
08/07/11   17:30
08/07/11   19:00
09/07/11   19:00

我目前在我的WHERE声明中有一条规则,因此显示今天之间的所有日期(所以它将是05/07/11直到3年后的同一日期05/07/14)。

我还想在WHERE语句下添加另一条规则,以便它只显示当前时间前两小时的时间(当前日期等于表中的日期)。

所以在05/07/11 19:00它应该显示:

Date       Time        Field3        Field4 - etc.
--------------------------------------------------
05/07/11   17:45       blah          blah
05/07/11   19:45       blah          blah
08/07/11   17:30
08/07/11   19:00
09/07/11   19:00

同一天21:46,现在应该显示:

Date       Time        Field3        Field4 - etc.
--------------------------------------------------
08/07/11   17:30
08/07/11   19:00
09/07/11   19:00

我如何在SQL中执行此操作?我认为它必须是一个if then或case当时声明,但我还没有能够解决它?

ALSO日期是在VB.Net中生成的,所以时间也是如此。当前的sql(和工作)代码是:

SELECT m.MatchID Manage, m.Date, m.Time, t.TeamCode "Home", b.TeamCode "Away", 
g.GroundName "Ground", ( SUBSTRING(u.GivenName,1,1) + '. ' + RTRIM(u.Surname) ) AS Referee, 
( SUBSTRING(v.GivenName,1,1) + '. ' + RTRIM(v.Surname) ) AS "Assistant 1", 
( SUBSTRING(w.GivenName,1,1) + '. ' + RTRIM(w.Surname) ) AS "Assistant 2", 
a.FOfficialID, a.AssessorID, a.RefereeAID, a.AReferee1AID, a.AReferee2AID, 
a.FOfficialAID, a.AssessorAID, 'Details' "Details", t.AgeGroupID, r.WetWeatherID 

FROM Match m 
LEFT OUTER JOIN Appointment a ON m.MatchID=a.MatchID 
LEFT OUTER JOIN WetWeather r ON r.MatchID=m.MatchID 
INNER JOIN Team t ON m.HomeTeamID=t.TeamID 
INNER JOIN Team b ON m.AwayTeamID=b.TeamID 
INNER JOIN Ground g ON g.GroundID=m.GroundID 
LEFT OUTER JOIN Users u ON u.UserID=a.RefereeID 
LEFT OUTER JOIN Users v on v.UserID=a.AReferee1ID 
LEFT OUTER JOIN Users w on w.UserID=a.AReferee2ID 

WHERE (m.Date BETWEEN '05-Jul-2011' AND '05-Jul-2014') 

3 个答案:

答案 0 :(得分:3)

如果您使用数据库时间和日期字段,则可以简单地与当前日期/时间进行比较

…
WHERE `Date` > NOW()
AND `Time` > NOW()

答案 1 :(得分:3)

添加列日期和时间以及间隔-2小时+ 3年的比较。

select *
from YourTable
where Date+cast(Time as datetime) between dateadd(hour, -2, getdate()) and dateadd(year, 3, getdate())

不确定上述查询中是否可以使用Date上的任何索引。如果您遇到性能问题,可以尝试这样做。使用Date索引可能会做得更好。

select *
from YourTable
where Date between cast(getdate() as date) and dateadd(year, 3, getdate()) and
      Date+cast(Time as datetime) > dateadd(hour, -2, getdate())

答案 2 :(得分:1)

我会通过加入子查询来实现。类似的东西:

     select ...
     from Match as m
     inner join
        (select mSub.MatchID, 
        case when Date+cast(Time as datetime) between dateadd(hour,-2,getdate()) 
             and getdate() then 1 else 0 end as Show
        from Match as mSub
        where Date between 
           cast(getdate() as date)
           and cast(dateadd(year,3,getdate()) as date)
         ) as Control
      on Control.MatchID=m.MatchID

因此,子查询会为您提供可在CASE语句中使用的Show列,并进行过滤。