Link to home
Start Free TrialLog in
Avatar of gracie1972
gracie1972Flag for United States of America

asked on

Date Diff in SQL

In access would add this to my criteria: > CDate("1/1/" & Year(Now())-1  to get anything greater than 1/1/YYYY.  I need to calculate YTD metrics as well as PY YTD metrics.  

YTD:  1/1/2016-present
PYTD: 1/1/2015-12/31/2015

How can I translate this to SQL?  I need to automate this.
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Year - CAST(CAST(Year(SomeDate) as char(4)) + '0101' as date)

What's the logic for PYTD?  That can wildly differ from place to place, so check out my article SQL Server Calendar Table which gives you code and a demo on how to pull this off to handle custom periods.
Avatar of gracie1972

ASKER

For Prior Year I have to include all the dates greater than 1/1/2015.  (Current year - 1).

In access this worked:  > CDate("1/1/" & Year(Now())-1
datediff (year,1,getdate ())
That gives you the number of years from 1901 until this year

Now add that to "year zero" (1900)

dateadd (year, datediff (year,1,getdate ()) ,0)

Which will return a datetime value of:
Jan 1 last year
This only returned greater than 1/1/2016, I need for this query to run and by default always go back 1 year, YTD starting at the beginning of the year.  

When I write the where statement like this, I only get > 1/1/2016.
WHERE dbo.VW_Tableau_Sell_Out.[WEEK] > dateadd (year, datediff (year,1,getdate ()) ,0)

If today were 7/19/2017, then the query should return > 1/1/2016, we are trying to automate this. Access cannot work any longer the data pulls are too large.
This worked in Access: WHERE (dbo_VW_Tableau_Sell_Out.WEEK)>CDate("1/1/" & Year(Now())-1)
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia 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
Thank you!