mssql选择GETDATE - 从00:00到23:59全天

时间:2014-05-08 12:55:52

标签: sql sql-server

运行MS SQL Server 2008

我有这个问题:

select count(*) from dbo.study
where study_datetime >= (GETDATE() -1)

将所有昨天的考试都写回我的学习表。如果我今天要求它完成所有事情,我怎么能让它回来?例如,我今天将从00:00:00-000 - 当前时间

获取所有内容

我在'study_datetime'列中的值如下所示:2014-05-06 10:40:31.000

我似乎无法想出这个。我试过用'0'代替'-1',但我得到0结果。

感谢

4 个答案:

答案 0 :(得分:2)

遗憾的是,oracle中没有trunc(),但是因为你有2008版本,你可以使用:

select count(*) from dbo.study where study_datetime >= cast(getDate() As Date)

答案 1 :(得分:1)

如果我理解得很好(同一天的值),我认为您可以使用DATEDIFF函数,将日期作为日期部分。

select count(*) from dbo.study
where datediff(dd, study_datetime, GETDATE()) = 0
and study_datetime  <= GETDATE() -- if you need a check for the "future" (datetime after GETDATE() )

答案 2 :(得分:0)

从dbo.study中选择count(*) 其中study_datetime:2014-05-06 00:00:00 and:2014-05-06 23:59:59。

它可能对你有帮助

答案 3 :(得分:0)

要获得今天严格要求的所有内容,请使用:

select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
and study_datetime < cast(DATEADD(day,1,getdate()) as Date)

当您使用连续数据时,切换到使用半开放时间间隔几乎总是更好,以确保数据分成一个且恰好一个时间间隔。通常,当你想要&#34;整天&#34;时,你不想排除在一天的最后一分钟发生的事情(例如23:59:37.223或甚至23:59:59.993 )。因此,您通常会将查询写为>= midnight at the start of the day< midnight at the start of the following day(请注意不同类型的比较)

这通常比尝试计算今天的最后一刻并使用<=(或BETWEEN)进行比较更好。

相关问题