2014-03-28 48 views
1

的条款我有一个查询这使我上个月的完成数据如何获得在的Sql

select * from Tabl 
where datepart(month, completed_date) = DATEPART(month, getDate())-1 
and datepart(year, completed_date) = datepart(year, getDate()) 

这个条件,但它给了我错误的数据时,当前的日期是在一月

如何如果当前月份是1月份,我是否可以编写条件以返回正确的数据?

+0

改变你的方法,以便你的where子句查找completed_date> = something和completed_date <在其他事物之后的那一天。它会以这种方式运行得更快。至于得到这些变量,这取决于你如何调用这个查询。如果它来自应用程序代码,则可能更容易使用它。否则,你可以使用tsql。 –

回答

2

SQL Server的DATEADD函数将在这里帮助你。

​​

使用的“MM”只是月份的关键字。

1

嗯,尝一口一个月的日期,而不是减去:

select * 
from Tabl 
where month(completed_date) = month(dateadd(month, -1, getdate()) and 
     year(completed_date) = year(dateadd(month, -1, getdate()); 

但是,如果你在completed_date有一个指标,最好是把所有的操作上getdate()这样的表达是“优化搜索”(也就是说,可以使用索引):

where completed_date >= cast(dateadd(month, -1, getdate() - day(getdate() + 1) as date) and 
     completed_date < cast(getdate() - day(getdate()) 

当你减去从日期的“月日”,你得到的前一个月的最后一天。

0
select * from Tabl 
where 
    datepart(year, completed_date) * 100 + datepart(month, completed_date) 
    < 
    datepart(year, getDate()) * 100 + datepart(month, GetDate())