Katmai (Sql 2008) - Group By Sets

With Sql 2008 (in the current CTP you have in your hand), thanks to a new extension to the group by clause referred to as 'grouping sets', you now have the ability to use sets of grouping columns in your group by clauses, allowing you to define basically multiple groupings in the same single query - i.e., instead of providing a single group by column-set, you can define multiple 'sets' of grouping columns, and have the resultset include the concatenated results for each set (think of this as effectively the UNION ALL of multiple identical select statements that are grouped by different column sets).

Some sample code showing some simple usage is here below, enjoy!

  use tempdb;
  go
  if object_id('dbo.tblGroupTest') > 0
   drop table dbo.tblGroupTest;
  create table dbo.tblGroupTest (id int, year smallint, quarter smallint, month smallint, amt bigint);
  go
  -- Fill up some sample yearly, quarterly, monthtly data for 2000 - 2007...
  declare @i int
  set @i = 2000
  while @i <= 2007 begin
   insert dbo.tblGroupTest (id, year, quarter, month, amt)
   select row_number() over (order by a.object_id),
     @i,
     ntile(4) over (order by a.object_id),
     ntile(12) over (order by a.object_id),
     a.object_id
   from (
     select object_id from sys.columns
     union all
     select object_id from sys.columns
     ) a;
 
   set @i = @i+1;
  end
  go
 
  -- Report
  select year,
    case when grouping(quarter) = 1 then '-- TOTAL --' else cast(quarter as varchar(5)) end as quarter,
    case when grouping(month) = 1 then '-- TOTAL --' else cast(month as varchar(5)) end as month,
    sum(amt) as sumAmt, avg(amt) as avgAmt
  from dbo.tblGroupTest
  group by grouping sets (
   (year, quarter, month),
   (year, quarter),
   (year)
  )
  order by year, isnull(quarter,10), isnull(month,15);

Chad Boyd ~~~ This posting is provided "AS IS" with no warranties, and confers no rights. Use of any included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.