For a current project I am working I need to return an aggregate report based on date ranges.
I have 3 types of reports, yearly, monthly and daily.
To assist in returning this report I need a function that will return all of the sub-ranges of datetimes, within a big range.
So for example if I as for all the daily ranges between '2006-01-01 11:10:00' and '2006-01-05 08:00:00' I would expect the following results.
select *
from dbo.fnGetDateRanges('d', '2006-01-01 11:10:00', '2006-01-05 08:00:00')
2006-01-01 11:10:00.000, 2006-01-02 00:00:00.000
2006-01-02 00:00:00.000, 2006-01-03 00:00:00.000
2006-01-03 00:00:00.000, 2006-01-04 00:00:00.000
2006-01-04 00:00:00.000, 2006-01-05 00:00:00.000
2006-01-05 00:00:00.000, 2006-01-05 08:00:00.000
For the yearly range of '2006-01-01 11:10:00' to '2009-05-05 08:00:00', I would expect.
select *
from dbo.fnGetDateRanges('y', '2006-01-01 11:10:00', '2009-05-05 08:00:00')
2006-01-01 11:10:00.000, 2007-01-01 00:00:00.000
2007-01-01 00:00:00.000, 2008-01-01 00:00:00.000
2008-01-01 00:00:00.000, 2009-01-01 00:00:00.000
2009-01-01 00:00:00.000, 2009-05-05 08:00:00.000
How would I implement this function?