Sunday, January 18, 2015

MSSQL : Find Last Day and First Day of the month, and previous month

Get First Day of this month
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) 

Get Last Day of this month
SELEC DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))) 

Get First Day of the last (1) month
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0)

Get Last Day of the last (1) month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0))+1,0)))

Get First Day of the last (2) month
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 2, 0) 

Get Last Day of the last (2) month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 2, 0))+1,0))) 

and so on...

No comments: