我有这样的用户定义函数:
create FUNCTION dbo.FormattedTimeDiff (@Date1 DATETIME, @Date2 DATETIME)
RETURNS VARCHAR(10)
AS BEGIN
DECLARE @DiffSeconds INT = sum(DATEDIFF(SECOND, @Date1, @Date2) )
DECLARE @DiffHours INT = @DiffSeconds / 3600
DECLARE @DiffMinutes INT = (@DiffSeconds - (@DiffHours * 3600)) / 60
DECLARE @RemainderSeconds INT = @DiffSeconds % 60
DECLARE @ReturnString VARCHAR(10)
SET @ReturnString = RIGHT('00' + CAST(@DiffHours AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(@DiffMinutes AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(@RemainderSeconds AS VARCHAR(2)), 2)
RETURN @ReturnString
END
我尝试像这样执行:
SELECT
t.vtid,
dbo.FormattedTimeDiff(PayDate, DelDate)
FROM
dbo.Transaction_tbl t
where t.Locid = 5
但是我得到这样的输出:
vtid
----------- ----------
7 00:21:42
7 01:05:30
7 00:37:43
7 NULL
8 00:00:42
8 00:07:25
7 00:25:36.
我想获得vtid 7和8的日期差异总和
预期产出:
vtid
7 01:25:45
8 00:07:45
我尝试过分组但显示错误,所以我必须在存储过程中进行更改?
答案 0 :(得分:1)
那么,在这种情况下,您需要更改“ your ”函数以使用秒作为输入参数 - 而不是两个日期:
CREATE FUNCTION [dbo].[FormattedTimeDiffFromSeconds] (@Seconds INT)
RETURNS VARCHAR(10)
AS BEGIN
DECLARE @DiffHours INT = @Seconds / 3600
DECLARE @DiffMinutes INT = (@Seconds - (@DiffHours * 3600)) / 60
DECLARE @RemainderSeconds INT = @Seconds % 60
DECLARE @ReturnString VARCHAR(10)
SET @ReturnString = RIGHT('00' + CAST(@DiffHours AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(@DiffMinutes AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(@RemainderSeconds AS VARCHAR(2)), 2)
RETURN @ReturnString
END
然后你可以进行选择,以秒为单位总结时差,并对其进行格式化:
SELECT
v.Vtype,
SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) as sum_min,
dbo.FormattedTimeDiffFromSeconds(SUM(DATEDIFF(SECOND, t.Paydate, t.DelDate))),
AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(MI, t.Paydate, t.DelDate))) as avg_min
FROM
dbo.Transaction_tbl t
LEFT JOIN
dbo.VType_tbl v ON t.vtid = v.vtid
WHERE
t.transactID IN (24, 25)
GROUP BY
v.Vtype