Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 SQL where子句表示两个日期正好相隔一个月减去一秒?_Sql Server 2008 - Fatal编程技术网

Sql server 2008 SQL where子句表示两个日期正好相隔一个月减去一秒?

Sql server 2008 SQL where子句表示两个日期正好相隔一个月减去一秒?,sql-server-2008,Sql Server 2008,我在一个表中有两个datetime列,我想精确地选择那些从第一列到第二列的差异是一个月短一秒的行。例如,它将为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-

我在一个表中有两个datetime列,我想精确地选择那些从第一列到第二列的差异是一个月短一秒的行。例如,它将为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
然而,例如,选择2012年,必须考虑闰年

我将如何撰写这样一份声明

SELECT *
FROM Table
WHERE col2 = DATEADD(second, -1, (DATEADD(Month, 1 Col1)))
-- check for either direction
OR col1 = DATEADD(second, -1, (DATEADD(Month, 1 Col2)))
这表示,“显示column2比col1多(一个月,一秒钟)的行。”


SQL Server中内置的日期逻辑会自动解释闰年之类的情况。

+1请注意,OP可能希望比较是双向的,例如,两个方向上的差异。