SQL - 计算TIME之间的持续时间

时间:2017-01-24 14:35:54

标签: sql sql-server sql-server-2008 time duration

我有以下两个例子约会

enter image description here

第二次约会从晚上7点到午夜。但是持续时间可以追溯到19个小时。这是因为没有存储日期,它计算了前一天晚上7点到午夜之间的差异。

任命只能安排到午夜,所以当选择假设即将到来的夜晚的午夜而不是前一天晚上时,有一些SQL会将这一天增加1天吗?这应该只在午夜时间有效,否则它会正常工作。

当前SQL

select mr.AssignmentId, ABS(DATEDIFF(MINUTE, mr.AssignmentStart, mr.AssignmentEnd) /60.0) as Total

from master_rota mr

enter image description here

4 个答案:

答案 0 :(得分:3)

好吧,不要使用abs()

select mr.AssignmentId,
       (case when mr.AssignmentStart < AssignmentEnd
             then DATEDIFF(MINUTE, mr.AssignmentStart, mr.AssignmentEnd) / 60.0
             else 24 + DATEDIFF(MINUTE, mr.AssignmentStart, mr.AssignmentEnd) / 60.0
        end) as Total
from master_rota mr;

实际上,我认为我更喜欢这个等效的版本:

select mr.AssignmentId,
       (DATEDIFF(MINUTE, mr.AssignmentStart, mr.AssignmentEnd) / 60.0 + 
        (case when mr.AssignmentStart < AssignmentEnd then 0 else 24 end)
       ) as Total
from master_rota mr;

只有一个地方有datediff()

答案 1 :(得分:0)

您应该让您的应用程序执行插入以实际执行正确的插入逻辑。但是,似乎这可能是一种解决方法:

SELECT mr.AssignmentId
     , DATEDIFF(MINUTE, mr.AssignmentStart, 
         CASE WHEN mr.AssignmentEnd < mr.AssignmentStart THEN mr.AssignmentEnd + 1 ELSE mr.AssignmentEnd END) /60.0 as Total    
FROM master_rota mr

答案 2 :(得分:0)

如果是午夜,请在第二天更改为00:00:00

#!/ sr/bin/python
heigth = float(input("Enter the height of the person: "))
sex = input("Enter the person's gender:")

if(sex == "male"):
        pi = (72.7 * heigth) - 58
elif(sex=="female"):
        pi = (62.1 * heigth) - 44.7
else:
        print("Invalid gender")

print("The ideal weight for this person is:",pi)

答案 3 :(得分:0)

如果AssignmentEnd是午夜(00:00),只需添加一天。

SELECT mr.AssignmentId,
    CASE WHEN mr.AssignmentEnd = '00:00'
         THEN DATEDIFF(MINUTE, mr.AssignmentStart, DATEADD(DAY, 1, mr.AssignmentEnd)) / 60.0
         ELSE DATEDIFF(MINUTE, mr.AssignmentStart, mr.AssignmentEnd) / 60.0
    END AS Total
from master_rota mr;