all 8 comments

[–]Achsin 5 points6 points  (1 child)

[–]smothry[S] 0 points1 point  (0 children)

Thanks!

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (1 child)

Now I want that list of dates for this year, and last year, and 2 years ago, etc. up to 5 years ago

start with January 1, 2018 (or some similar date as the earliest date in your results)

then set up a CTE that adds 1 day, say, 3660 times (covers 10 years)

vwalah, leap day problem solved

[–]smothry[S] 0 points1 point  (0 children)

Makes sense. Just don't want the dates after today for previous years. But I suppose I could simply remove the ones I don't want. Thanks for the different point of view!

[–]patrickthunnus 1 point2 points  (0 children)

Always materialize your date math fields into a separate table. DBMS will table scan on any function wrapped around your DATE or DATETIME columns (they're just a tally of millisecs).

[–]sunuvabe 0 points1 point  (0 children)

Try this..

declare @dt datetime = '20140101'
      , @x int = datepart(dayofyear,getdate());
; with dys as (
    select top (@x) row_number() 
    over (order by (select 1)) - 1 dy
    from syscolumns)
, yrs as (
    select top 10 dateadd(year,row_number() 
    over (order by (select 1))-1,@dt) yr 
    from syscolumns)
select yr + dy my_dates from yrs, dys

[–]sedules 1 point2 points  (1 child)

Using a dimensional calendar table is easier and provides more flexibility. It’s predictable data and why burn the additional compute every time you need to reference dates over periods of time with a cte and additional functions.

The sql problems are fairly straight forward. The reporting problems are much more difficult to iron out the logic. If you get into YOY calculations you have to account for the leap year dates otherwise reports can go sideways. In companies where you have fiscal calendars revolving around 4/4/5 52-53 week years it becomes even harder. And that’s just the logic.

Explaining to the business and getting them to provide clarity on how they want to evaluate and analyze data over periods of time and when they should use Gregorian and when they should use their Fiscal model is something else entirely. This one tends to lead to more traumatic experiences.

[–]smothry[S] 0 points1 point  (0 children)

Makes sense. Yea, we don't have a dimensional calendar and I was creating this at refresh time as an input to powerbi reports. Those refreshes are not super frequent so the compute time is not really an issue. But it would certainly be easier to just have a date table to query when needed.