简体   繁体   English

如何在 SQL Server 中以小时、天、分钟、秒显示浮点数

[英]how to show float numbers in Hours, Day, Minute, Second in SQL Server

I have a simple record in table below:我在下表中有一个简单的记录:

Depart_dt                    Arrived_dt
10/1/2013 6:15:00 AM         10/1/2013 7:25:00 AM    

Based on my calculation, it is 1 hour and 10 min.根据我的计算,它是1小时10分钟。 Thanks to VKP, I used the datediff function as below:感谢 VKP,我使用了 datediff 函数,如下所示:

Select 
Dateiff (DD, depart_dt, arrived_dt) as day,
Dateiff (HH, depart_dt, arrived_dt) as hour,
Dateiff (Minute, depart_dt, arrived_dt) as min,
Date if (second, depart_dt, arrived_dt) as second 
from temp

However, my result looks funny with the minute and second columns但是,我的结果在分钟和第二列中看起来很有趣

Day   Hour   Min   Second 
0     1      70    4200

The hour appears correct but I am not sure how it comes to 70 in min column and 4200 in second column?小时看起来是正确的,但我不确定分钟列中的 70 和第二列中的 4200 是如何计算的?

sorry guys, I was wrong.对不起各位,我错了。 Yes, 70 min is correct because that is 1 hour and 10 min.是的,70 分钟是正确的,因为那是 1 小时 10 分钟。 Please disregard this请无视这个

You can just use DATEDIFF to get the difference as an integer.您可以仅使用DATEDIFF将差异作为整数获取。

select item, 
datediff(dd, start_dt, end_dt) as total_days,
datediff(hh, start_dt, end_dt) as total_hours,
datediff(minute, start_dt, end_dt) as total_minutes,
datediff(second, start_dt, end_dt) as total_seconds
from yourtable

When using datediff you'll have to understand what it does.使用 datediff 时,您必须了解它的作用。 The name is quite confusing, because it doesn't actually calculate date differences, but according the documentation : "Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate."该名称非常令人困惑,因为它实际上并不计算日期差异,但根据文档:“返回指定开始日期和结束日期之间跨越的指定日期部分边界的计数(有符号整数)。”

That means that for example datediff hour for 06:15 and 07:00 is 1 hour.这意味着例如 06:15 和 07:00 的 datediff 小时是 1 小时。

You'll probably want something like this:你可能想要这样的东西:

DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])/86400 as Days,
((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)/3600) as Hours,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)/60) as Minutes,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)%60) as Seconds

This calculates the amounts in full days / hours etc so number of hours will never be 24 or more.这以全天/小时等计算金额,因此小时数永远不会是 24 或更多。

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

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