sqlsql-serverdatetimedatediffssms-2014

Trying to a Select Count where it needs to count the difference between a certain date and current date


It's not quite working for me!

My query is as follows:

SELECT COUNT (*) as [generic] 
FROM [Log]
Where value IN (Select ID, tsSendDocument, sysReceivedFrom
WHERE sysReceivedFrom = 'generic' AND 
DATEDIFF(hour, tsSendDocument, GetDate()) > 2) 

So, what am I doing wrong here?

I want it to to count every time the tsSendDocument column is older than 2 hours. It will eventually give me a count that's equal to 1. I have a table set up to alert me if the value = 1, which means that the tsSendDocument is older than 2 hours.

Do this make any sense?


Solution

  • As per your comment, I've understood that you want to check if the last entry is older than 2 hours, so this should work:

    SELECT TOP 1 CASE WHEN tsSendDocument < DATEADD(HOUR, -2, GETDATE()) THEN 1 ELSE 0 END AS [generic]
    FROM [Log]
    ORDER BY tsSendDocument DESC