我的过程中SQL的总和时间如何返回:
START -- FINISH --- TOTAL
18:14:47 20:32:54 02:18:06
12:35:45 15:06:06 02:30:21
18:08:26 21:25:39 03:17:12
我需要总和列TOTAL(08:05:40)
我的存储过程:
Alter PROCEDURE [dbo].[timeTotal]
@userName nvarchar(50)
AS
BEGIN
SELECT
CONVERT(VARCHAR(8),dateadd(HH,7,workStart),108) AS workStart,
CONVERT(VARCHAR(8),dateadd(HH,7,workFinish),108) AS workFinish,
CONVERT(VARCHAR(8),workFinish - workStart,108) AS total
FROM workTime
WHERE userName = userName
END
我需要得到08:05:40
答案 0 :(得分:1)
要以小时计算时差,请使用以下内容:
SELECT
(RIGHT('00' + CONVERT(VARCHAR(10), SUM(DATEDIFF(MINUTE, FromTime, ToTime)) / 60), 2)
+ ':' +
RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(Minute, FromTime, ToTime)) % 60), 2)
+ ':' +
RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(SECOND, FromTime, ToTime)) % 60), 2))
AS TotalTime FROM AllocateRoom
在存储过程中使用上述内容,它返回时差之和,如下所示:
01:20:20
最后您的预期数据如下:
;WITH DEMO(ID, FromTime, ToTime) AS
(
SELECT TOP 1
ID
,CONVERT(DATETIME,FromTime,120) AS FromTime
,CONVERT(DATETIME,ToTime,120) AS ToTime
FROM (VALUES (1,'2016-09-03 18:14:47.000','2016-09-03 20:32:54.000')
,(2,'2016-09-03 12:35:45.000','2016-09-03 15:06:06.000')
) AS X(ID,FromTime,ToTime)
)
SELECT
k.ID,
k.FromTime,
k.ToTime,
DATEADD(SECOND,DATEDIFF(SECOND, k.FromTime, k.ToTime),CONVERT(TIME(0),'00:00:00',0)) AS TIME_DIFF,
DATEADD(SECOND,SUM(DATEDIFF(SECOND, k.FromTime, k.ToTime)) OVER
(
PARTITION BY (SELECT NULL)
),CONVERT(TIME(0),'00:00:00',0)) AS TIME_SUM
FROM DEMO k;
答案 1 :(得分:0)
使用DATEDIFF()而不是减法来查找2个日期之间的时间
DATEDIFF(SECOND, workStart, workFinish) AS total
以HH:MM:SS,
显示CONVERT(VARCHAR(8), DATEADD(SECOND, 0, DATEDIFF(SECOND, workStart, workFinish)),108) AS total