Here's one way:select dateadd(day, (datediff(day, 0, dt)/7)*7, 0) as [7DayPeriodStarting] ,count(*) as [RowCount]from ( select '2006-01-08 23:00:25.000' dt union all select '2006-01-08 23:00:24.000' union all select '2006-01-08 23:00:24.000' union all select '2006-01-08 23:00:25.000' union all select '2006-01-08 23:00:25.000' union all select '2006-01-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' ) agroup by dateadd(day, (datediff(day, 0, dt)/7)*7, 0)output:7DayPeriodStarting RowCount ------------------------------------------------------ ----------- 2006-01-02 00:00:00.000 62006-02-06 00:00:00.000 3
Another way would be to incorporate a Numbers or Calandar table. That might give you more control on exactly what days each bucket should cover. The above method only returns "buckets" that have rows.EDIT:a simpler form of the (above) code would just be this the following. I guess you should post your desire output.select datediff(day, 0, dt)/7 as [BucketID] ,count(*) as [RowCount]from ( select '2006-01-08 23:00:25.000' dt union all select '2006-01-08 23:00:24.000' union all select '2006-01-08 23:00:24.000' union all select '2006-01-08 23:00:25.000' union all select '2006-01-08 23:00:25.000' union all select '2006-01-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' union all select '2006-02-08 23:00:25.000' ) agroup by datediff(day, 0, dt)/7output:BucketID RowCount ----------- ----------- 5531 65536 3
Be One with the OptimizerTG