Skip to content
Advertisement

How to get how many hour 4AM have there been between two dates in TSQL

I need to get how many of a specific hour have occurred between two dates in TSQL. Some examples:

The following would give the result = 1

The following would give the result = 0, as there has been 0 4AMs in between

The following would give the result = 2, as there has been 2 4AMs in between

The following would give the result = 2, as there has been 2 4AMs even though they are just on the 4:00AM time

I have tried something like this… but it is giving an incorrect answer

Anyone who can shed some light I would appreciate it

Advertisement

Answer

The easiest way would be to remove 4 hours from both values, and then get the difference in days:

Seems the OP wants to count the event of 04:00 as well. I therefore remove a further second from the start time:

If you’re actually storing values accurate to 1/300 of a second, then don’t use 1 second, use 3 millseconds, to ensure utmost accuracy.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement