Link to home
Start Free TrialLog in
Avatar of LCNW
LCNWFlag for United States of America

asked on

SQL Previous month and YTD

I need to expand on a solution that I received here. I wanted to get the past 3 months of data from the current date with each month separate. For example:

(@MyDate>= DATEADD(month, DATEDIFF(month, 0, GETDATE()) - 2, 0)) AND (@MyDate< DATEADD(month, DATEDIFF(month, 0, GETDATE()) - 1, 0))

This would get data from 2 months ago. I'm now being tasked to get data from 2 months ago plus ytd at that point in time. So, November 2012 and January 2012 - November 2012. I need this to be dynamic as the months shift. Any suggestions?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Steve Wales
Steve Wales
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LCNW

ASKER

This works great until I start a new year. I need it to reset at that point. For instance, in January it does January 2013 back to January 2012. I would only want January 2013 back to January 2013 as it's a new year.
If you're wanting YTD based upon the current date instead of the beginning date, just use getdate() as shown in the blog post ?
Avatar of LCNW

ASKER

I think I need to do something where I say AND year=year. This way it keeps the YTD on the correct year. I'm just not sure how to code it.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LCNW

ASKER

I haven't been able to figure out the code for the second part of my logic. Thanks for the help.