GROUPING()

Use the GROUPING() clause with ROLLUP to determine whether null values are the result of a ROLLUP operation or part of your dataset. GROUPING() returns 1 if the null value is a subtotal generated by a rollup. It returns 0 otherwise.

This example uses the GROUPING() function and CASE statements together to label the subtotal and grand total categories. The first case checks for a null value generated by the rollup in the Category field. If true, then the query labels the field "All Categories." Similarly, the second case checks whether a Sub-Category field is null. If true, the query labels the field "All Sub-Categories."

SELECT
(CASE WHEN GROUPING("Category") = 1 THEN 'All Categories' ELSE "Category" END) as "Category",
(CASE WHEN GROUPING("Sub_Category") = 1 THEN 'All Sub-Categories' ELSE "Sub_Category" END) as "SubCategory",
SUM("Sales") as "sum_sales"
FROM "Superstore"
GROUP BY ROLLUP("Category", "Sub_Category");
Category Sub-Category sum_sales
Furniture Bookcases 114,880
  Chairs 328,449.1
  Furnishings 91,705.16
  Tables 206,965.53
  All Sub-Categories 741,999.8
Office Supplies Appliances 107,532.16
  Art 27,118.73
  Binders 203,412.73
  Envelopes 16,476.4
  Fasteners 3,024.28
  Labels 12,486.31
  Paper 78,479.21
  Storage 223,843.61
  Supplies 46,673.544
  All Sub-Categories 719,047.03
Technology Accessories 167,380.32
  Copiers 149,528.03
  Machines 189,238.63
  Phones 330,007.05
  All Sub-Categories 838,154.03
All Categories All Sub-Categories 2,297,200.86