关于统计工时以及跨日时间换算解决方案

65 阅读1分钟

统计时间的方法可以使用SQL函数DATEDIFF()来进行计算,但统计工时不允许使用以下写法

 -- 这样会损失很大的精度
 DATEDIFF(hour, a.BeginTime, a.EndTime)
 -- 一般采取分钟相减然后换算为小时
 DATEDIFF(minute, a.BeginTime, a.EndTime)
 int hour = minute / 60;

跨天如果获取的数据为像BEGINtIME = '2023-07-21 08:45:59.654' ENDTIME = '2023-07-22 01:00:59.154'的数据则直接相减然后换算小时即可,但如果数据只有小时数的话那就需要处理一下。

 CASE
     WHEN a.BeginTime is not null and a.EndTime is not null then
         CASE
             WHEN a.EndTime = '1799-01-01 00:00:00' THEN DATEDIFF(MINUTE, a.BeginTime, '1799-01-01 23:59:00.000') + 1
             ELSE DATEDIFF(MINUTE, a.BeginTime, a.EndTime)
         END
     ELSE 0
 END

附带时间转换字符串方法

 SELECT convert(varchar(26), getdate(), 23)      -- 2023-07-21
 SELECT convert(varchar(26), getdate(), 24)      -- 13:51:46
 SELECT convert(varchar(26), getdate(), 25)      -- 2023-07-21 13:51:46.700
 SELECT convert(varchar(26), getdate(), 120)     -- 2023-07-21 13:51:46

datediff 此函数返回指定的日期和时间startdateenddate 之间所跨的指定 datepart 边界的计数(作为带符号整数值)

 DATEDIFF ( datepart , startdate , enddate )