gracie1972
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.
YTD: 1/1/2016-present
PYTD: 1/1/2015-12/31/2015
How can I translate this to SQL? I need to automate this.
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
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
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
ASKER
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.[W EEK] > 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.W EEK)>CDate ("1/1/" & Year(Now())-1)
When I write the where statement like this, I only get > 1/1/2016.
WHERE dbo.VW_Tableau_Sell_Out.[W
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.W
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
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.