This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to find the date of Third Sunday of all the months.
Input Year:
1 |
2017 |
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Sundays ---------- 2017-01-15 2017-02-19 2017-03-19 2017-04-16 2017-05-21 2017-06-18 2017-07-16 2017-08-20 2017-09-17 2017-10-15 2017-11-19 2017-12-17 |
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
;WITH CTE AS ( SELECT DATEFROMPARTS(2017,1,1) FirstDay ,DATENAME(DW, DATEFROMPARTS(2017,1,1)) Day_Name UNION ALL SELECT DATEADD(d,1,FirstDay) FirstDay ,DATENAME(DW, DATEADD(d,1,FirstDay)) Day_Name FROM CTE WHERE FirstDay < DATEFROMPARTS(2017,12,31) ) SELECT FirstDay as Sundays FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Months ORDER BY Months) rnk FROM ( SELECT *, MONTH(FirstDay) Months FROM CTE WHERE Day_Name = 'Sunday' ) t )t WHERE rnk = 3 OPTION (MAXRECURSION 0) |
Please try the different solution for this puzzle and share it via comment...