-1

我有这样的用户定义函数:

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 

我尝试给 group by 但显示错误,所以我必须在我的存储过程中进行更改?

4

1 回答 1

1

那么,在这种情况下,您需要更改“您的”函数以使用秒作为输入参数 - 而不是两个日期:

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
于 2013-07-21T08:54:53.383 回答