-1

我有一张transaction这样的桌子:

transactID    Paydate                   DelDate                     vtid
24            2013-05-08 16:53:03.000   2013-05-08 17:00:28.000     8
25            2013-05-08 16:34:38.000   2013-05-08 17:00:14.000     7

我写了这样的查询来获取日期差异的总和:

select 
    v.Vtype, 
    SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) as sum_min,
    AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(MI, t.Paydate, t.DelDate))) as avg_min
from 
    Transaction_tbl t 
left join 
    VType_tbl v on t.vtid = v.vtid 
where 
    t.transactID in (24, 25) 
group by 
    v.Vtype

我在几分钟内得到了正确的输出:

Vtype           sum_min     avg_min
----- ----------- ---------------------------------------
Normal             26          26.000000
VIP                7           7.000000 

我不想在几分钟内获得sum_min列,而是想在hh:mm:ss. 所以我的预期输出应该是这样的:

Vtype           sum_min              avg_min
----- ----------- ---------------------------------------
Normal            00:26:00          26.000000
VIP                00:7:00           7.000000

为了得到这个,我写了这样的查询:

 SELECT 
     convert(varchar(10), sum(DATEDIFF(hour, t.Paydate, t.DelDate))) + ':' +
     convert(varchar(10), sum(DATEDIFF(minute, t.Paydate, t.DelDate) % 60)) + ':' +
     convert(varchar(10), sum(DATEDIFF(SECOND, t.Paydate, t.DelDate) % 60)) AS 'HH:MM:SS'
FROM 
     Transaction_tbl t 
WHERE 
     t.transactID in (24, 25) 
group by 
     vtid 

但在我的输出中,1 小时是额外的。执行此查询时,我得到如下输出:

 HH:MM:SS
--------------------------------
1:26:36
1:7:25

那么如何重新编写查询以获得正确的结果呢?

4

2 回答 2

0

如果要将分钟或秒转换为hh:mm:ss格式,则可以使用以下函数(DATEADD、CONVERT样式为 114和 LEFT):

DECLARE @PayDate     DATETIME,
        @DelDate     DATETIME,
        @DiffSeconds INT,
        @DiffMinutes INT;

SELECT  @PayDate='2013-05-08T16:53:03.000',
        @DelDate='2013-05-08T17:00:28.000',
        @DiffSeconds=DATEDIFF(SECOND,@PayDate,@DelDate),
        @DiffMinutes=DATEDIFF(MINUTE,@PayDate,@DelDate);


SELECT  @DiffSeconds AS Diff_Seconds,
        LEFT(CONVERT(VARCHAR(50),DATEADD(SECOND,@DiffSeconds,0),114),8) AS Diff_From_Seconds,
        @DiffMinutes AS Diff_Minutes,
        LEFT(CONVERT(VARCHAR(50),DATEADD(MINUTE,@DiffMinutes,0),114),8) AS Diff_From_Minutes;

结果:

Diff_Seconds Diff_From_Seconds Diff_Minutes Diff_From_Minutes
------------ ----------------- ------------ -----------------
445          00:07:25          7            00:07:00
于 2013-07-21T09:55:12.307 回答
0

marc_s 对他的评论是正确的。您需要的是这个答案中的功能。

然后你会这样称呼它:

SELECT 
     udfTimeSpanFromSeconds(SUM(DATEDIFF(SECOND, t.Paydate, t.DelDate))) AS 'HH:MM:SS'
FROM 
     Transaction_tbl t 
WHERE 
     t.transactID in (24, 25) 
group by 
     vtid 
于 2013-07-21T09:50:31.813 回答