-- Query 6-2: same as query 6, but with a "grouping_id" column. SELECT calendar_year_lookup.year, outlet_lookup.state, outlet_lookup.shop_name, (calendar_year_lookup.year IS NULL) * 4 + (outlet_lookup.state IS NULL) * 2 + (outlet_lookup.shop_name IS NULL) AS niveau_global, SUM(shop_facts.amount_sold) AS total_amount_sold, SUM(shop_facts.quantity_sold) AS total_quantity_sold FROM outlet_lookup INNER JOIN shop_facts ON shop_facts.shop_code = outlet_lookup.shop_code INNER JOIN calendar_year_lookup ON shop_facts.week_key = calendar_year_lookup.week_key -- Note: "Grouping sets" is only available on Oracle SQL, so it is manually recreated here GROUP BY calendar_year_lookup.year ASC, outlet_lookup.state, outlet_lookup.shop_name ASC WITH ROLLUP;