BBampaa

Lessons › SQL › Deep Dive: Advanced Window Functions

SQL lesson

CUBE for cross-tabulation

CUBE generates every possible combination of subtotals across a set of columns - all individual breakdowns, every mix of two or more, and the grand total - in a single query.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Creating Retail Cross-Tab Totals with CUBE

SELECT category, region, channel, SUM(revenue) AS total_revenue
FROM store_sales
GROUP BY CUBE(category, region, channel)

Result:

categoryregionchanneltotal_revenue
ElectronicsNorthOnline12400.0
Electronics21150.5
North23900.0
Online17700.0
36751.25

Step by step

  1. Run the query without SUM so you can see what the unfiltered values look like.
    SELECT category, region, channel, revenue
    FROM store_sales
    GROUP BY CUBE(category, region, channel);
  2. SUM totals the numbers in a column. Works on numeric columns only.
    SELECT category, region, channel, SUM(revenue)
    FROM store_sales
    GROUP BY CUBE(category, region, channel);
  3. AS gives the SUM result a friendly column name so the output reads cleanly.
    SELECT category, region, channel, SUM(revenue) AS total_revenue
    FROM store_sales
    GROUP BY CUBE(category, region, channel);

Practice

Try each one in your head first, then open the answer.

1. Using orders, write a query that returns all combinations of order_id and customer_id totals using CUBE.
SELECT order_id, customer_id, COUNT(*) FROM orders GROUP BY CUBE(order_id, customer_id)
2. Using store_sales, write a query that returns all combinations of sale_id and store_id totals using CUBE.
SELECT sale_id, store_id, COUNT(*) FROM store_sales GROUP BY CUBE(sale_id, store_id)
3. Using products, write a query that returns all combinations of product_id and brand totals using CUBE.
SELECT product_id, brand, COUNT(*) FROM products GROUP BY CUBE(product_id, brand)
4. Using reviews, write a query that returns all combinations of review_id and product_id totals using CUBE.
SELECT review_id, product_id, COUNT(*) FROM reviews GROUP BY CUBE(review_id, product_id)
5. Using employees, write a query that returns all combinations of employee_id and full_name totals using CUBE.
SELECT employee_id, full_name, COUNT(*) FROM employees GROUP BY CUBE(employee_id, full_name)

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed