简体   繁体   English

如何在SQL Server中比较日期时间?

[英]How to compare datetime in SQL Server?

I have to show the date 2018/01/30 if the datetime is between 2018/01/30 04:59:59.000 and 2018/01/31 04:59:59.000 如果日期时间介于2018/01/30 04:59:59.0002018/01/31 04:59:59.000之间,我必须显示日期2018/01/30

I have a table called DataEntry . 我有一个名为DataEntry的表。 I want to move those records by date as per my criteria. 我想按我的标准按日期移动这些记录。

This DataEntry table have TransferTime that datatype is datetime. 此DataEntry表的TransferTime数据类型为datetime。

As per my criteria if the TransferTime is 2018/01/30 01:30:59.000 then the date should be 2018/01/29 根据我的标准,如果TransferTime为2018/01/30 01:30:59.000则日期应为2018/01/29

I think you can simply just write like this: 我认为您可以简单地这样写:

select 
 case when DATEPART(HOUR,'2018/01/30 01:30:59.000') >= 05 then cast('2018/01/30 01:30:59.000' as date) 
      else cast(dateadd(Dd,-1,'2018/01/30 01:30:59.000' )as date) 
 end 

This is somewhat of a guess on vague logic, but perhaps using CONVERT and DATEADD ? 这有点模糊逻辑上的猜测,但也许使用CONVERTDATEADD吗?

WITH VTE AS(
    SELECT CONVERT(datetime2(3),DT) AS DT
    FROM (VALUES('20180130 04:59:59.000'),('20180131 01:00:34.000'),('20180130 01:30:59.000')) V(DT))
SELECT CONVERT(date, DATEADD(SECOND, -17999,DT)) AS D, DT
FROM VTE;

It's worth noting that you, oddly, state that '20180130 04:59:59.000' AND ''20180131 04:59:59.000' should both be on the same day, ( '20180130' ). 值得注意的是,您奇怪地指出'20180130 04:59:59.000' ''20180131 04:59:59.000'应该都在同一天( '20180130' )。 This doesn't make any sense, as Days don't overlap like that. 这没有任何意义,因为Days不会那样重叠。 Thus the latter time would show '20180131' , as it's exactly 24 hours later. 因此,后者时间将显示为'20180131' ,因为恰好是24小时后。

If the former time should actually be '20180129' , then change -17999 to -18000 , or SECOND,-17999 to HOUR, -5 . 如果是前者的时间实际上应该是'20180129' ,然后更改-17999-18000 ,或SECOND,-17999HOUR, -5

this will do too: 这也可以做到:

select cast(dateadd(second, -17999,Transfertime) as date)

being 17999 = 4hs59m59s in seconds 是17999 = 4hs59m59s以秒为单位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM