简体   繁体   中英

DateDiff returns negative value in sql

I am doing some calculation in SQL Query using DateDiff function. My Calculation went wrong if DateDiff Value came in negative

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

Two Columns VendorTicketRaisedOn & ClosedOn are of type DateTime . If ClosedOn > VendorTicketRaisedOn Then Value Came in negetive.

How to treat this case to produce result as 0 ?

If Value is in negative then DateDiff should give output as 0 instead of -value

DB : SQL SERVER 2008

Query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM