I want to split a given year into given number of date range pieces using SQL. Following points need to be considered while splitting it:
-
Given year will always start from 01-01 and end at 12-31 and it should be split into given number of pieces based on months. For example:
year SplitCount output 2019 2 2019-01-01 2019-07-01 2019 3 2019-01-01 2019-05-01 2019-09-01
- If user asks to split given year into 12 pieces, it should split the whole year into 12 months.
- If user asks to split given year more then 12 pieces, it should split it into week wise
Please suggest.
Best Answer
Try this:. It uses DateFromParts(year, month, 1) to find the correct month for any value 1..12 or it uses DateAdd(week, date) to figure for any value 13..52. This way, we let the database engine worry about pesky things like leap year for us rather than doing that kind of math on our own.
This
Gives:
This
Gives:
This
Gives: