I have two datetime columns in a table, and I would like to select precisely those rows whose difference from the first column to the second column is one second short of one month. For example, it would select these rows (and no others) for datetimes in the year 2011:
col1 col2
2011-01-01 00:00:00 2011-01-31 23:59:59
2011-02-01 00:00:00 2011-02-28 23:59:59
2011-03-01 00:00:00 2011-03-31 23:59:59
2011-04-01 00:00:00 2011-04-30 23:59:59
2011-05-01 00:00:00 2011-05-31 23:59:59
2011-06-01 00:00:00 2011-06-30 23:59:59
2011-07-01 00:00:00 2011-07-31 23:59:59
2011-08-01 00:00:00 2011-08-31 23:59:59
2011-09-01 00:00:00 2011-09-30 23:59:59
2011-10-01 00:00:00 2011-10-31 23:59:59
2011-11-01 00:00:00 2011-11-30 23:59:59
2011-12-01 00:00:00 2011-12-31 23:59:59
However, selecting for 2012, for example, would have to account for the leap year.
How would I write such a statement?
This says, “Show me rows where column2 is (one month more and one second less) than col1.”
The built in date logic in SQL Server automatically accounts for things like leap years.