SELECT warehouse, product, SUM(quantity) qty FROM inventory GROUP BY warehouse, product UNION ALL SELECT warehouse, null, SUM(quantity) qty FROM inventory GROUP BY warehouse UNION ALL SELECT null, product, SUM(quantity) qty FROM inventory GROUP BY product UNION ALL SELECT null, null, SUM(quantity) qty FROM inventory; SQL