DateDiff在sql中返回负值

时间:2013-05-15 06:55:44

标签: sql sql-server sql-server-2008

我正在使用DateDiff函数在SQL Query中进行一些计算。如果DateDiff值为负数

,则我的计算出错了
Declare @ActualTime Numeric(10,2)=677.00

Select Convert(Numeric(10,2),(100*((@ActualTime-(Convert(Numeric(10,2),CONVERT(VARCHAR(10),SUM(DATEDIFF(Minute,VendorTicketRaisedOn ,ClosedOn)) / 60)+'.'+
      Right('00'+CONVERT(VARCHAR(2),SUM(DATEDIFF(Minute, VendorTicketRaisedOn , ClosedOn)) % 60),2))))/@ActualTime*1)))[AGS Uptime %]
      From Ticket

两列VendorTicketRaisedOn& ClosedOn的类型为DateTime。如果ClosedOn> VendorTicketRaisedOn然后价值变成了新的。

如何处理此案例以将结果生成为0?

如果Value为负数,则DateDiff应将输出设为0而不是-value

DB:SQL SERVER 2008

1 个答案:

答案 0 :(得分:1)

查询:

Declare @ActualTime Numeric(10,2)=677.00

SELECT CASE WHEN ClosedOn > VendorTicketRaisedOn 
            THEN 0
       ELSE Convert(Numeric(10,2),(100*((@ActualTime-(Convert(Numeric(10,2),CONVERT(VARCHAR(10),SUM(DATEDIFF(MINUTE,VendorTicketRaisedOn ,ClosedOn)) / 60)+'.'+ Right('00'+CONVERT(VARCHAR(2),SUM(DATEDIFF(MINUTE, VendorTicketRaisedOn , ClosedOn)) % 60),2))))/@ActualTime*1)))
      END AS [AGS Uptime %]
FROM Ticket