DateAdd& DateDiff在一起

时间:2015-07-17 09:15:07

标签: sql sql-server

我有以下查询,希望选择所有记录;

  • ActualMinutes是大于或等于ScheduledMinutes和
  • 的5
  • ActualMinutes是小于或等于ScheduledMinutes。

E.g。如果ScheduledMinutes是60,我想要任何介于55和15之间的ActualMinutes。 65(含)。

SELECT *
FROM
    (
        SELECT top 10000
        DateDiff(MI, StartTime, EndTime) as ScheduledMinutes, 
        DateDiff(MI, SignIn, SignOut) as ActualMinutes,
        *
        FROM tblRosteredCare 
        WHERE SignIn != 'M' AND SignOut != 'M' 
    ) DT
WHERE DT.ActualMinutes <= DT.ScheduledMinutes

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

从另一个中减去一个并进行比较:

SELECT *
FROM
    (
        SELECT top 10000
        DateDiff(Minute, StartTime, EndTime) as ScheduledMinutes, 
        DateDiff(Minute, SignIn, SignOut) as ActualMinutes,
        *
        FROM tblRosteredCare 
        WHERE SignIn != 'M' AND SignOut != 'M' 
    ) DT
WHERE DT.ActualMinutes - DT.ScheduledMinutes between -5 and 5

或者很可爱并使用ABS

SELECT *
FROM
    (
        SELECT top 10000
        DateDiff(Minute, StartTime, EndTime) as ScheduledMinutes, 
        DateDiff(Minute, SignIn, SignOut) as ActualMinutes,
        *
        FROM tblRosteredCare 
        WHERE SignIn != 'M' AND SignOut != 'M' 
    ) DT
WHERE ABS(DT.ActualMinutes - DT.ScheduledMinutes) <= 5