我有一张像这样的表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
那么如何才能重新编写查询以获得正确的结果?
答案 0 :(得分:0)
然后你会这样称呼它:
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
答案 1 :(得分:0)
如果您想将分钟或秒转换为hh:mm:ss
格式,那么您可以使用这些函数(DATEADD,CONVERT with style 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