Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.

If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).

If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.

Thanks,

Shahsra

like image 476
Shahsra Avatar asked Mar 23 '11 21:03

Shahsra


2 Answers

Today including time info  : getdate()
Today without time info    : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month    : DATEADD(month, datediff(month, 0, getdate())-1, 0)

so most likely

WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
  AND dateColumn <  DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
like image 94
RichardTheKiwi Avatar answered Oct 19 '22 22:10

RichardTheKiwi


Step back one month, subtract the number of days to the current date, and add one day.

WHERE  
  DateField <= GetDate() AND
  DateField >= DateAdd(
      mm, 
      -1, 
      DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
  )

To remove the time quickly, you can use this Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )

So the second part would be (without time)

DateField >= Cast( Floor( Cast( (DateAdd(
          mm, 
          -1, 
          DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
      )) AS FLOAT ) ) AS DATETIME )
like image 21
Russell Steen Avatar answered Oct 19 '22 23:10

Russell Steen