我有SQL表格,其中DateDiff的格式为(hh.mm)
DateDiff ATM
1.45 121
1.50 121
1.50 121
当我在ATM上Sum
{Date}的Group by
时,会显示
4.45 121
但实际的日期时差应为
5.25 121
我们如何在SQL查询中实现相同的功能
Select Sum(Cast(Convert(Varchar(10),DATEDIFF(HOUR,TicketRaisedOn,ClosedOn))+'.'+
Convert(Varchar(10),DATEDIFF(MINUTE,TicketRaisedOn,ClosedOn)%60) as Numeric(18,2)))[Down Time],ATM
From Ticket Where Closed=1 And DATEPART(DAYOFYEAR,GETDATE())=DATEPART(DAYOFYEAR,TicketRaisedOn)
Group BY ATM Order By [Down Time] Desc
TicketRaisedOn
& ClosedOn
属于DateTime
数据库是SQL Server 2008
上面的查询会打印出这样的结果(但是它的错误,因为它将数字加起来而不是日期时间格式)
Down Time ATM
16.95 282
14.46 1811
14.20 52
14.04 936
样本数据
Select TicketRaisedOn,ClosedOn,ATM
From Ticket
Where ATM=282 And DATEPART(DAYOFYEAR,GETDATE())=DATEPART(DAYOFYEAR,TicketRaisedOn)
And Closed=1
TicketRaisedOn ClosedOn ATM
2012-12-21 01:15:23.793 2012-12-21 15:11:59.240 282
2012-12-21 16:42:29.820 2012-12-21 18:21:30.797 282
答案 0 :(得分:3)
你在做什么不起作用,因为1.5代表一个半小时,不一小时50分钟。
要获得您想要的效果,请以小单位(例如秒)进行算术运算,然后将其转换为日期时间,然后将日期时间转换为最终表示形式。这是一个例子:
select right(convert(varchar(255),
DATEADD(second, DATEDIFF(s, TicketRaisedOn,ClosedOn), cast(0 as datetime)),
120),
8)
答案 1 :(得分:3)
在格式化之前进行求和
SELECT
ATM,
CONVERT(VARCHAR(10), SUM(DATEDIFF(Minute, TicketRaisedOn, ClosedOn)) / 60)
+ '.' +
RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(Minute, TicketRaisedOn, ClosedOn)) % 60), 2)
FROM Ticket
GROUP BY ATM
Sql Fiddle:http://sqlfiddle.com/#!3/eca01/1