【发布时间】:2014-08-14 10:52:50
【问题描述】:
我正在使用 sql server 2008。 我想获取从上个月到查询运行那一刻的所有数据(在“where”子句中)。 例如,如果今天是 14.8.2014,它将收集 1.7.2014 到 31.7.2014 之间的所有信息
【问题讨论】:
标签: sql sql-server-2008 date
我正在使用 sql server 2008。 我想获取从上个月到查询运行那一刻的所有数据(在“where”子句中)。 例如,如果今天是 14.8.2014,它将收集 1.7.2014 到 31.7.2014 之间的所有信息
【问题讨论】:
标签: sql sql-server-2008 date
这是一个简单的方法:
where year(datecol) * 12 + month(datecol) = year(getdate()) * 12 + month(datecol) - 1
这个表达式不是“sargable”,这意味着查询不能利用索引。如果您有一张大表并且这很重要,那么您可以进行日期算术:
where datecol >= dateadd(month, -1, cast( (getdate() - datepart(day, getdate()) + 1) as date)) and
datecol < cast( (getdate() - datepart(day, getdate()) + 1) as date)
【讨论】:
那是什么解决了它:
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate())) AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
【讨论】:
date_created 上的任何索引。我强烈推荐 Gordan 回答中的第二种解决方案。
不要尝试一个月的最后一天,像这样使用“下个月的第一天”更容易也更可靠(注意使用小于):
select
*
from tables
where (
dateField >= "1st of this Month"
and
dateField < "1st of Next Month"
(
计算:
SELECT
GETDATE()
AS "getdate with time"
, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
AS "getdate time truncated"
, DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
AS "day 1 this month"
, DATEADD(MONTH, 1, DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)))
AS "day 1 next month"
;
所以:
select
*
from tables
where (
dateField >= DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0)) -- "1st of this Month"
and
dateField < DATEADD(month,1,DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0))) -- "1st of Next Month"
(
【讨论】: