2014-03-28 63 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())