Sql 在where子句中捕获当前月份的第一个到当前日期的日期范围
我正在选择客户id、名称和服务日期等字段。我试图在where子句中写道,每天运行查询时,它都会捕获从当月第一天到当天的日期范围。一种方法是比较月份和年份:Sql 在where子句中捕获当前月份的第一个到当前日期的日期范围,sql,sql-server-2012,Sql,Sql Server 2012,我正在选择客户id、名称和服务日期等字段。我试图在where子句中写道,每天运行查询时,它都会捕获从当月第一天到当天的日期范围。一种方法是比较月份和年份: where year(col) = year(getdate()) and month(col) = month(getdate()) and day(col) <= day(getdate()) -- this is optional, if there is no future data (假设表中没有未
where year(col) = year(getdate()) and
month(col) = month(getdate()) and
day(col) <= day(getdate()) -- this is optional, if there is no future data
(假设表中没有未来的数据。)
或者,更好的是:
where col >= datefromparts(year(getdate()), month(getdate()), 1)
一种方法是比较月份和年份:
where year(col) = year(getdate()) and
month(col) = month(getdate()) and
day(col) <= day(getdate()) -- this is optional, if there is no future data
(假设表中没有未来的数据。)
或者,更好的是:
where col >= datefromparts(year(getdate()), month(getdate()), 1)
编辑:我使用了BETWEEN来捕捉可能的未来日期/计划事件
编辑:我使用了BETWEEN来捕捉可能的未来日期/计划事件
剩下的应该很简单。提示日期介于DATEADD(month,DATEDIFF(month,0,@mydate),0)和@mydate之间,其余的应该很简单。提示日期添加(月,日期差异(月,0,@mydate),0)和@mydate之间的日期