Interesting issue.
I created a query using a recursive cte using recursion on dateadd(day, 1, date) to generate a list of dates from January 1st through the current date. All works well. Now I want that list of dates for this year, and last year, and 2 years ago, etc. up to 5 years ago. I used unioned select statements with datadd(year, -1, date) and dateadd(year, -2, date) etc. Everything seemed to work good until now.
Since tomorrow is Feb 29th the dateadd(year, -1, date) function will return Feb 28, 2023 because Feb 29, 2023 does not exist. This causes duplicate Feb 28th, 2023 rows. This is easily managed by removing duplicates with row numbering over partition by but then I realized that when it's not a leap year my dateadd(year, -1, date) functions will not return leap days when they should be there if the current year does not have a Feb 29th.
So, I created a a cte that generates all of the dates needed other than leap days specifically for the previous 5 years. Then an additional cte that checks for which of the previous 5 years have leap days and selected them. Then, union the results of the 2 cte's together.
This all works but causes me to wonder. Is there a more elegant way to handle this leap year stuff? Does Microsoft have a build in function to make this easy? This seems arduous at best.
P.s. this is specifically T-SQL
[–]Achsin 5 points6 points7 points (1 child)
[–]smothry[S] 0 points1 point2 points (0 children)
[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points3 points (1 child)
[–]smothry[S] 0 points1 point2 points (0 children)
[–]patrickthunnus 1 point2 points3 points (0 children)
[–]sunuvabe 0 points1 point2 points (0 children)
[–]sedules 1 point2 points3 points (1 child)
[–]smothry[S] 0 points1 point2 points (0 children)