This question really baffled me, cos I couldn't actually come up with a simple solution for it. Damn.
Best I could manage was an absolute bastardization of the following where you create a Temp Table, insert the "Periods" into it, join back to your original table, and group off that.
Assume your content table has the following
ID int
Date DateTime
Counter int
And you're trying to sum all the counter
's in six month periods
DECLARE @min_date datetime
select @min_date = min(date) from test
DECLARE @max_date datetime
select @max_date = max(date) from test
DECLARE @today_a datetime
DECLARE @today_b datetime
set @today_a = getdate()
set @today_b = getdate()
CREATE TABLE #temp (startdate DateTime, enddate DateTime)
WHILE @today_a > @min_date
BEGIN
INSERT INTO #temp (startDate, endDate) VALUES (dateadd(month, -6, @today_a), @today_a)
SET @today_a = dateadd(month, -6, @today_a)
END
WHILE @today_b < @max_date
BEGIN
INSERT INTO #temp (startDate, endDate) VALUES (@today_b, dateadd(month, 6, @today_b))
SET @today_b = dateadd(month, 6, @today_b)
END
SELECT * FROM #temp
SELECT
sum(counter),
'Between ' + Convert(nvarchar(10), startdate, 121) + ' => ' + Convert(nvarchar(10), enddate, 121) as Period
FROM test t
JOIN #Temp ht
ON t.Date between ht.startDate AND ht.EndDate
GROUP BY
'Between ' + Convert(nvarchar(10), startdate, 121) + ' => ' + Convert(nvarchar(10), enddate, 121)
DROP TABLE #temp
I really hope someone can come up with a better solution my brain has obviously melted.