CUBE (a, b) produces every subset of its columns, (a, b), (a), (b), (): 2^n groupings, the classic OLAP cube. Does a coupon change basket size, and does it differ by channel?
SELECT coalesce(channel, '(all)') AS channel, coalesce(promo, '(all)') AS promo,
count(DISTINCT order_id) AS orders, round(avg(gross_amount), 2) AS avg_line
FROM (SELECT *, CASE WHEN coupon IS NULL THEN 'none' ELSE 'coupon' END AS promo
FROM mart.sales WHERE status <> 'cancelled') s
GROUP BY CUBE (channel, promo)
ORDER BY 1, 2;Output
channel | promo | orders | avg_line ---------+--------+--------+---------- (all) | (all) | 94110 | 25.43 (all) | coupon | 7579 | 25.36 (all) | none | 86531 | 25.44 android | (all) | 32869 | 25.39 ... web | coupon | 1520 | 26.22 web | none | 17503 | 25.43
Twelve rows answer both questions: coupons did not raise the average line in this sample data, except slightly on the web. coalesce labels rolled-up rows safely only because neither column has NULLs. Cubes grow fast (five dimensions give 32 groupings), so list just the combinations you need with GROUPING SETS.