GROUP BY ROLLUP

ROLLUP is a sub-clause of GROUP BY that creates and displays aggregations of column data. The results output of ROLLUP is based on column order in your query.

ROLLUP supports the following aggregate functions.

  • Average
  • Count
  • Min
  • Max
  • Sum

This example first groups the results by category and sub-category, and runs Sum(Profit), an aggregate function on each resulting row. By modifying theGROUP BY clause with ROLLUP, the query “rolls up” the results into subtotals and grand totals.

Notice how GROUP BY ROLLUP (Category, Sub_Category) creates groups for each column combination:

The query first groups the total profit for each subcategory of a given category. Next, it groups is the total profit for a single category. Once each category’s total profit is accounted for, the query generates the total profit for all categories.

CategorySub-CategoryTotalProfit
FurnitureBookcases-3,472.56
 Chairs25,590.17
 Furnishings13,059.14
 Tables-17,725.48
 -18,451.27
Office SuppliesAppliances18,138.01
 Art6,527.79
 Binders30,221.76
 Envelopes6,964.18
 Fasteners949.52
 Labels5,546.25
 Paper34,053.57
 Storage21,278.83
 Supplies-1,189.1
 -122,490.8

You can also group by multiple columns. This query generates the group of cities that contain stores in each category. The count column shows how many stores there are in each city.

Here are the first ten results.

CategoryCitycnt
FurnitureAkron2
 Alexandria3
 Allen1
 Allentown1
 Amarillo4
 Anaheim8
 Andover1
 Apopka1
 Apple Valley2