我需要计算所有座席的'登录'总时间。
+-----------------------+-------------+-----------------------+-----------------------+
|ShiftDateAndTime |EmployeeID |LoginTime |LogoutTime |
+-----------------------+-------------+-----------------------+-----------------------+
|2017-03-07 08:59:56.000| 81200 |2017-03-07 08:59:56.000|2017-03-07 17:30:43.000|
+-----------------------+-------------+-----------------------+-----------------------+
|2017-03-07 07:35:12.000| 82300 |2017-03-07 07:35:12.000|2017-03-07 16:04:30.000|
+-----------------------+-------------+-----------------------+-----------------------+
|2017-03-07 09:38:58.000| 81800 |2017-03-07 09:38:58.000|2017-03-07 18:02:59.000|
+-----------------------+-------------+-----------------------+-----------------------+
|2017-03-07 09:18:52.000| 83240 |2017-03-07 09:18:52.000|2017-03-07 18:08:54.000|
+-----------------------+-------------+-----------------------+-----------------------+
我想计算所有代理商2017-03-07的总累计工时。例如,
Sum(LogoutTime - LoginTime for Agent1, Agent2, Agent3 and Agent4.)
我需要hh:mm:ss
的时间。我正在使用SQL Server 2014来运行查询。
我试过了:
选择
(SUM(datediff(second,LoginTime,LogoutTime))/ 3600)[TotalTime]
来自AgentStats
但我只在几分钟内得到时间。我需要它......:mm:ss。
答案 0 :(得分:1)
我使用CTE只是为了便于将结果格式化为HH:MM:SS
WITH acm AS
(
SELECT SUM (DATEDIFF(second, LoginTime, LogoutTime)) [Seconds]
FROM @AgentStats
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, ShiftDateAndTime)) = CAST('2017-03-07' AS DATETIME)
)
SELECT CONVERT(VARCHAR(10),Seconds/3600)
+':'
+ RIGHT('00'+CONVERT(VARCHAR(2),(Seconds%3600)/60),2)
+':'
+ RIGHT('00'+CONVERT(VARCHAR(2),Seconds%60),2) AS [HH:MM:SS]
FROM acm;
结果是:
HH:MM:SS
34:14:08
在此处查看:http://rextester.com/EHCSY33410
由于您只选择了一天,因此无需按ShiftDateAndTime进行分组。
<强>更新强>
我建议创建一个INLINE用户自定义函数,以便在大型查询中使用它更简单易用。
CREATE FUNCTION dbo.SecondsToHMS(@Seconds int)
RETURNS table
AS
RETURN
(
SELECT CONVERT(VARCHAR(20), @Seconds / 3600) + ':'
+ RIGHT('00' + CONVERT(VARCHAR(2), (@Seconds % 3600) / 60) ,2) + ':'
+ RIGHT('00' + CONVERT(VARCHAR(2), @Seconds%60), 2) AS [HMS]
);
GO
然后可以将以前的查询更改为:
SELECT (SELECT HMS FROM dbo.SecondsToHMS(SUM (DATEDIFF(second, LoginTime, LogoutTime)))) [HMS]
FROM @AgentStats
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, ShiftDateAndTime)) = CAST('2017-03-07' AS DATETIME)
GO
/*
|HMS |
|:-------|
|34:14:08|
*/
dbfiddle here