Monday, October 22, 2012

Date Function with Queries


Date Function with Queries

First day of previous month= 1) We substract number of days in the month from our date (20) and we get last day of previous month.
2) We add one day to get first day of current month.
3) We go one month back so first day of the month stays the same and
SELECT DATEADD(m,-1, Dateadd(d,1-DATEPART(d,getdate()),GETDATE())) AS [First Day of Previous Month]

first day of month=Select Dateadd(d,1-DATEPART(d,getdate()),GETDATE()) as [First Day of the Month]
we used getdate() function to get current date. We have also used datepart functin with d argument and today's date that returns day of the month. Now that we have these arguments we used DateAdd function and substracted from today's date numbers of days (eg if we have 16th of May 2011 we subctract from this date 16 days) and the trick is to add one day to get first day of month.
last day of previous month
Select Dateadd(d,-DATEPART(d,getdate()),GETDATE()) as [Last Day of Previous Month]
last day of month =
Select Dateadd(d,-DATEPART(d,DateAdd(m,1,getdate())),DateAdd(m,1,getdate())) as [Last Day of Month]
We add 1 month to todays date and from the result we minus number of days in this particular month. This way we get last day of current month.

No comments:

Post a Comment