Expand description
E5.4 — PIVOT / UNPIVOT SQL macro rewrite layer.
DataFusion does not parse PIVOT or UNPIVOT natively. This module rewrites
those constructs into equivalent standard SQL before passing the query to DataFusion.
§PIVOT rewrite
SELECT * FROM sales
PIVOT (SUM(amount) FOR category IN ('food', 'tech', 'clothing'))becomes:
SELECT
SUM(CASE WHEN category = 'food' THEN amount END) AS "food",
SUM(CASE WHEN category = 'tech' THEN amount END) AS "tech",
SUM(CASE WHEN category = 'clothing' THEN amount END) AS "clothing"
FROM sales§UNPIVOT rewrite
SELECT * FROM monthly
UNPIVOT (value FOR month IN (jan, feb, mar))becomes a UNION ALL of individual SELECT statements:
SELECT 'jan' AS month, jan AS value FROM monthly
UNION ALL
SELECT 'feb' AS month, feb AS value FROM monthly
UNION ALL
SELECT 'mar' AS month, mar AS value FROM monthlyStructs§
- Pivot
Clause - Parsed representation of a PIVOT clause.
- Unpivot
Clause - Parsed representation of an UNPIVOT clause.
Functions§
- contains_
pivot - Returns
trueifsqlcontains aPIVOTclause (case-insensitive). - contains_
unpivot - Returns
trueifsqlcontains anUNPIVOTclause (case-insensitive). - parse_
pivot - Parse a simple
SELECT * FROM <source> PIVOT (<agg>(<col>) FOR <dim> IN (<vals>))statement. - parse_
unpivot - Parse a simple
SELECT * FROM <source> UNPIVOT (<val_col> FOR <name_col> IN (<cols>)). - rewrite_
pivot - Rewrite a PIVOT statement to equivalent
CASE WHENSQL. - rewrite_
pivot_ unpivot - Entry point: rewrite PIVOT or UNPIVOT if present, otherwise return unchanged.
- rewrite_
unpivot - Rewrite an UNPIVOT statement to a
UNION ALLof SELECT statements.