Listing 2: Materializing the Result Set in a Table SET NOCOUNT ON; USE tempdb; GO IF OBJECT_ID('dbo.MyGroupingSets', 'U') IS NOT NULL DROP TABLE dbo.MyGroupingSets; GO SELECT GROUPING_ID( custid, empid, YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ) AS grp_id, custid, empid, YEAR(orderdate) AS orderyear, MONTH(orderdate) AS ordermonth, DAY(orderdate) AS orderday, SUM(qty) AS qty INTO dbo.MyGroupingSets FROM dbo.Orders GROUP BY CUBE(custid, empid), ROLLUP(YEAR(orderdate), MONTH(orderdate), DAY(orderdate)); CREATE UNIQUE CLUSTERED INDEX idx_cl_grp_id_grp_attributes ON dbo.MyGroupingSets(grp_id, custid, empid, orderyear, ordermonth, orderday);