Pivot and unpivot with conditional aggregation
Overview
A pivot turns category values into named columns. An unpivot turns columns into category/value rows. For fixed channel names, conditional aggregation is portable across our target engines; dynamic category discovery and vendor-specific pivot operators are outside this example.
First example
SELECT region, SUM(CASE WHEN channel='online' THEN cents ELSE 0 END) AS online, SUM(CASE WHEN channel='store' THEN cents ELSE 0 END) AS store FROM analytics_sales GROUP BY region ORDER BY region;Observed SQLite result (rows in JSON):
[ [ "North", 150, 200 ], [ "South", 80, 0 ]]How it works
Our input has one sales row per transaction. SUM(CASE...) produces one result row per region; ELSE 0 defines missing channel totals as zero. UNION ALL stacks the columns back into rows without deduplication. The unpivot recreates aggregated summaries, not the original transaction IDs or multiplicities.
Practical example
WITH pivoted AS (SELECT region, SUM(CASE WHEN channel='online' THEN cents ELSE 0 END) AS online, SUM(CASE WHEN channel='store' THEN cents ELSE 0 END) AS store FROM analytics_sales GROUP BY region)SELECT region, 'online' AS channel, online AS cents FROM pivoted UNION ALL SELECT region, 'store', store FROM pivoted ORDER BY region, channel;Observed SQLite result (rows in JSON):
[ [ "North", "online", 150 ], [ "North", "store", 200 ], [ "South", "online", 80 ], [ "South", "store", 0 ]]Practice and mistakes
Add a third channel in a disposable copy. The fixed pivot will not include it unless you add a column or report an other bucket. Compare the total input amount with the sum of all pivot cells. Zero-filled absent categories cannot be distinguished from actual zero totals without counts.