Pivot y agregación condicional
Un informe pide una columna por valor (por estado, por medio de pago, por año) cuando los datos tienen una fila por valor. Escribe un agregado condicional por columna:
SELECT customer_id,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY customer_id;
Para un importe, SUM(CASE WHEN method = 'card' THEN amount END); para texto, MAX(CASE …). La operación inversa, el
unpivot, convierte una tabla ancha (una columna por trimestre) en filas: un SELECT por columna, unidos con
UNION ALL.
La trampa. COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) cuenta todas las filas: COUNT cuenta lo que
no es NULL, y 0 no es NULL. Usa SUM con ELSE 0, o COUNT sin ELSE. Además, los valores se escriben a mano: un
estado nuevo no tiene columna hasta que tú la añades, así que comprueba que la suma de las columnas coincide con el
total.
En tu almacén de datos. Postgres y DuckDB tienen la forma abreviada COUNT(*) FILTER (WHERE status = 'cancelled');
BigQuery usa COUNTIF(…), y Snowflake y Databricks, COUNT_IF(…). Snowflake, BigQuery y Databricks tienen
PIVOT (SUM(amount) FOR method IN ('card', 'paypal')) y UNPIVOT; Postgres no tiene ninguno de los dos; DuckDB escribe
PIVOT payments ON method USING SUM(amount).
La trampa
SELECT EXTRACT(YEAR FROM ordered_at) AS year,
COUNT(*) AS orders,
COUNT(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY EXTRACT(YEAR FROM ordered_at)
ORDER BY year;
| year | orders | delivered | cancelled |
|---|---|---|---|
| 2024 | 1291 | 1291 | 1291 |
| 2025 | 1209 | 1209 | 1209 |
La corrección
SELECT EXTRACT(YEAR FROM ordered_at) AS year,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY EXTRACT(YEAR FROM ordered_at)
ORDER BY year;
| year | orders | delivered | cancelled |
|---|---|---|---|
| 2024 | 1291 | 1108 | 79 |
| 2025 | 1209 | 966 | 70 |