Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.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 如何在SQL Server中选择最后三个月的所有日期_Sql Server_Date - Fatal编程技术网

Sql server 如何在SQL Server中选择最后三个月的所有日期

Sql server 如何在SQL Server中选择最后三个月的所有日期,sql-server,date,Sql Server,Date,我想从SQL Server中的表中选择所有最近3个月的日期 数据如下: Sunday 20-05-2012 Sunday 27-05-2012 Sunday 10-06-2012 Sunday 24-06-2012 Sunday 08-07-2012 Sunday 22-07-2012 Sunday 12-08-2012 Sunday 19-08-2012 Sunday 09-09-2012 Sunday 16-09-2012 尝试使用此查询: select date_column from

我想从SQL Server中的表中选择所有最近3个月的日期

数据如下:

Sunday 20-05-2012
Sunday 27-05-2012
Sunday 10-06-2012
Sunday 24-06-2012
Sunday 08-07-2012
Sunday 22-07-2012
Sunday 12-08-2012
Sunday 19-08-2012
Sunday 09-09-2012
Sunday 16-09-2012
尝试使用此查询:

select date_column from table_name
where datepart(m,date_column) > datepart(m,getdate())-3 and datepart(yy,date_column) >= datepart(yy,getdate())
尝试使用此查询:

select date_column from table_name
where datepart(m,date_column) > datepart(m,getdate())-3 and datepart(yy,date_column) >= datepart(yy,getdate())

将日期列保存为带有星期几的varchar-不好的主意。您无法编写更快的查询,因为必须始终转换字段,以便在where子句中使用它。此外,您的查询不能使用date_列的索引,每个查询将使用扫描索引

对于datetime列,查询应为:

select date_column
  from table_name
 where date_column between dateadd(m, -3, getdate()) and getdate()

将日期列保存为带有星期几的varchar-不好的主意。您无法编写更快的查询,因为必须始终转换字段,以便在where子句中使用它。此外,您的查询不能使用date_列的索引,每个查询将使用扫描索引

对于datetime列,查询应为:

select date_column
  from table_name
 where date_column between dateadd(m, -3, getdate()) and getdate()

欢迎使用StackOverflow:如果您发布代码、XML或数据示例,请在文本编辑器中突出显示这些行,并单击编辑器工具栏上的“代码示例”按钮(
{}
),以精确地格式化和语法突出显示它!你打算只在星期天回来吗?还是所有日期?欢迎使用StackOverflow:如果您发布代码、XML或数据示例,请在文本编辑器中突出显示这些行,并单击编辑器工具栏上的“代码示例”按钮(
{}
),以很好地格式化和语法突出显示它!你打算只在星期天回来吗?还是所有日期?感谢repaly,我收到了类似“从字符串转换日期时间时转换失败”这样的错误消息。我想您的日期列是字符串数据类型,而不是日期数据类型。因此,您必须使用字符串到日期的转换或字符串操作。尝试使用字符串操作的查询:选择temp_date from temp_dates,其中cast(子字符串(子字符串(temp_date,charindex('y',temp_date)+2,10),4,2)as int)>datepart(m,getdate())-3和cast(子字符串(子字符串(temp_date,charindex('y',temp_date)+2,10),7,4)as int)>=datepart(yy,getdate())该查询将像一只海龟,因为user1661868表中的字段类型错误。感谢Repay,我得到了类似“从字符串转换日期时间时转换失败”的错误消息。我想您的日期列是字符串数据类型,而不是日期数据类型。因此,您必须使用字符串到日期的转换或字符串操作。尝试使用字符串操作的查询:选择temp_date from temp_dates,其中cast(子字符串(子字符串(temp_date,charindex('y',temp_date)+2,10),4,2)as int)>datepart(m,getdate())-3和cast(子字符串(子字符串(temp_date,charindex('y',temp_date)+2,10),7,4)as int)>=datepart(yy,getdate())该查询将像一只海龟,因为user1661868表中的字段类型错误。从字符串转换datetime时转换失败日期列的类型是什么?varchar?从字符串转换日期时间时转换失败日期列的类型是什么?瓦查尔?