Átomo
39Up
CTE e subconsultas · SQL

UNPIVOT

Abrir na tabela

Definição

Transforma colunas em linhas. Útil para normalizar planilhas e tabelas largas.

UNPIVOT: Oracle, SQL Server, Snowflake, Databricks, BigQuery. Em outros bancos, use UNION ALL.

Exemplos

1. Meses de colunas para linhas
SELECT store_id, month, amount
FROM targets
UNPIVOT (amount FOR month IN (jan, feb, mar));
2. Forma portátil com UNION ALL
SELECT store_id, 'jan' AS month, jan AS amount FROM targets
UNION ALL
SELECT store_id, 'feb', feb FROM targets;
3. Mantendo os nulos (Oracle, Databricks)
SELECT store_id, month, amount
FROM targets
UNPIVOT INCLUDE NULLS (amount FOR month IN (jan, feb, mar));

No mesmo grupo