I’m trying to use the T-SQL function DATEDIFF to select the number of distinct dates in a time period.
The following query:
SELECT DATEDIFF(DAY, '2012-01-01 01:23:45', '2012-01-02 01:23:45')
selects 1, which is one less than I want. There are two distinct dates in the range: 2012-01-01 and 2012-01-02.
It is not correct to add one to the result in the general case. The following query:
SELECT DATEDIFF(DAY, '2012-01-01 00:00:00', '2012-01-02 00:00:00')
selects 1, which is correct, because there is only one distinct date in the range.
I’m sure there is a simple bit of arithmetic that I’m missing to calculate this. Can someone help me?
Given this example, it should still be
1, because there is only one day that has passed. Even if you are considering the start of a day, it would still be only one (as this range includes the start of only2012-01-02 00:00:00).Your logic for:
and
Should be the same, as mathematically they are the same range.
DATEDIFFcompares based on the granularity of the first paramter. You are comparing byday, so SQL Server will see2012-01-01to2012-01-02as a1day difference.An extremely ugly (and in my opinion, bad) workaround would be something like this:
What this would do is handle inclusive dates. So you could basically have this:
Would equal
2and this:Would equal
1. I don’t think this is the best idea in the world, but it will give you your desired output. It all boils down to business logic.