title: GROUP BY date ranges?
body: <p>I have the following stored Procedure:</p>
  
  <pre><code>SELECT tsks.grouping_ref, ttg.description AS grouping_desc, 
  SUM(ts.booked_time) AS booked_time_total, 
  DATENAME(MONTH, ts.start_dtm) + ' ' + DATENAME(YEAR, ts.start_dtm) AS month_name,
  @month_ref AS month_ref
  
  FROM timesheets ts
  JOIN timesheet_categories cat
  ON ts.timesheet_cat_ref = cat.timesheet_cat_ref
  
  JOIN timesheet_tasks tsks
  ON ts.task_ref = tsks.task_ref
  
  JOIN timesheet_task_groupings ttg
  ON tsks.grouping_ref = ttg.grouping_ref
  
  WHERE ts.status IN(1, 2) --Booked and approved
  AND cat.is_leave_category = 0 --Ignore leave
  --AND DATEPART(YEAR, ts.start_dtm) = @Year
  --AND DATEPART(MONTH, ts.start_dtm) = @Month
  
  --accounting months 2012
  AND (@month_ref = 81201 AND ts.start_dtm Between '2011-11-28' AND '2012-01-01')
    or (@month_ref = 81202 AND ts.start_dtm Between '2012-01-02' AND '2012-01-29')
    or (@month_ref = 81203 AND ts.start_dtm Between '2012-01-30' AND '2012-02-26')
    or (@month_ref = 81204 AND ts.start_dtm Between '2012-02-27' AND '2012-04-01')
    or (@month_ref = 81205 AND ts.start_dtm Between '2012-04-02' AND '2012-04-29')
    or (@month_ref = 81206 AND ts.start_dtm Between '2012-04-30' AND '2012-05-27')
    or (@month_ref = 81207 AND ts.start_dtm Between '2012-05-28' AND '2012-06-01')
    or (@month_ref = 81208 AND ts.start_dtm Between '2012-07-02' AND '2012-07-29')
    or (@month_ref = 81209 AND ts.start_dtm Between '2012-07-30' AND '2012-08-26')
    or (@month_ref = 81210 AND ts.start_dtm Between '2012-08-27' AND '2012-09-30')
    or (@month_ref = 81211 AND ts.start_dtm Between '2012-10-01' AND '2012-10-28')
    or (@month_ref = 81212 AND ts.start_dtm Between '2012-10-29' AND '2012-11-25')
  
  
  GROUP BY tsks.grouping_ref, ttg.description,
  DATENAME(MONTH, ts.start_dtm),
  DATENAME(YEAR, ts.start_dtm)
  ORDER BY grouping_desc
  </code></pre>
  
  <p>Essentially its filtering the results based on date ranges and then grouping the results like this:</p>
  
  <pre><code>Job Group | Month  | Booked Hours
  
     Test   | Feb 12 |    7
  </code></pre>
  
  <p>The user then clicks on Test where they will see a report on the 7 hours booked.
  I would like to group by based on the date ranges?</p>
  
  <p>I know that this creates the month:</p>
  
  <pre><code>DATENAME(MONTH, ts.start_dtm),
  DATENAME(YEAR, ts.start_dtm)
  </code></pre>
  
  <p>But the group by date ranges should only show up if there are results, i.e Test might be in range 1 so it will show up otherwise dont show the date ranges.</p>
  
  <p>Any ideas?</p>