如何在sql中减去两个日期列和两个时间列

问题描述 投票:0回答:2

我有4列

Startdate, 
enddate, 
starttime, 
endtime.  

我需要从enddate and endtime - startdate and starttime中减去。我需要从sql的四列中得到答案。

到目前为止,我找到了这个,但我认为这不会正常。

SELECT DATEDIFF (day, enddate, startdate) as NumberOfDays  
DATEDIFF(hour,endtime,starttime) AS NumberOfHours 
DATEDIFF(minute,endtime,starttime) AS NumberOfMinutes 
from table;

谢谢你的帮助

sql sql-server sql-server-2000 datediff subtraction
2个回答
0
投票

假设您有这样的数据,您可以将StartDate添加到StartTime以获取StartDateTime,对于EndDateTime也是如此

StartDate                StartTime                EndDate                  EndTime              
-----------------------  -----------------------  -----------------------  -----------------------
2014-05-01 00:00:00.000  1900-01-01 10:53:28.290  2014-05-07 00:00:00.000  1900-01-01 11:55:28.290

完成后,您可以获得如下所示的天数,小时数和分钟数:

select 
DATEDIFF(minute, StartDate + StartTime, EndDate + EndTime) / (24*60) 'Days',
(DATEDIFF(minute, StartDate + StartTime, EndDate + EndTime) / 60) % 24 'Hours',
DATEDIFF(minute, StartDate + StartTime, EndDate + EndTime) % 60 'Minutess'
  from YourTable

我们总是在几分钟内完成工作,以防止部分天过夜和部分小时跨越一小时的问题。


0
投票

编辑 - 现在我意识到问题是针对SQL Server 2000,这个建议的答案可能不起作用。

可以在https://www.microsoft.com/en-us/download/details.aspx?id=18819找到SQL Server 2000文档。安装完成后,在已安装的路径中查找tsqlref.chm,在该帮助文件中,您可以找到特定于DATEDIFF的信息。


根据原始问题的措辞,我假设开始/结束时间列的类型为TIME,这意味着没有日期部分。考虑到这一点,以下将回答您的问题。

但请注意,根据您的数据,您将在秒和毫秒方面失去精度。

更多关于DATEDIFF:https://msdn.microsoft.com/en-us/library/ms189794.aspx


DECLARE @mytable AS TABLE 
    (
        startdate DATETIME,
        enddate DATETIME,
        starttime TIME,
        endtime TIME
    )


INSERT INTO @mytable (startdate, enddate, starttime, endtime)
VALUES      (GETDATE() - 376, GETDATE(), '00:00:00', '23:59')

SELECT      *
FROM        @mytable

SELECT      DATEDIFF(HOUR, startdate, enddate) AS [NumHours],
            DATEDIFF(MINUTE, starttime, endtime) AS [NumMinutes]
FROM        @mytable

这将产生类似于以下的输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.