Posted by: newlynew May 3, 2010
SQL server roll-up function help
Login in to Rate this Post:     0       ?        

Here's an example. This should help.


Table:



Item Color Quantity
-------------------- -------------------- --------------------------
Table Blue 124
Table Red 223
Chair Blue 101
Chair Red 210

This query generates a subtotal report:





SELECT CASE WHEN (GROUPING(Item) = 1) THEN 'ALL'
            ELSE ISNULL(Item, 'UNKNOWN')
       END AS Item,
       CASE WHEN (GROUPING(Color) = 1) THEN 'ALL'
            ELSE ISNULL(Color, 'UNKNOWN')
       END AS Color,
       SUM(Quantity) AS QtySum
FROM Inventory
GROUP BY Item, Color WITH ROLLUP

Item                 Color                QtySum                    
-------------------- -------------------- --------------------------
Chair                Blue                 101.00                    
Chair                Red                  210.00                    
Chair                ALL                  311.00                    
Table                Blue                 124.00                    
Table                Red                  223.00                    
Table                ALL                  347.00                    
ALL                  ALL                  658.00                    

(7 row(s) affected)
Read Full Discussion Thread for this article