liveBook · Manning

Pivoting

As explained in DuckDB in Action

A pivot is a relational transformation that turns distinct values from rows into columns, typically while aggregating associated values.

Pivoting reorganizes grouped rows so distinct values become columns, usually while aggregating associated measures. It turns a system-and-year result into a spreadsheet-style report with one row per system and one column per year. section 4.7

Static and dynamic energy pivots

A portable static form hardcodes the desired columns: SELECT system_id, sum(kWh) FILTER (WHERE year(day) = 2019) AS 'kWh in 2019', sum(kWh) FILTER (WHERE year(day) = 2020) AS 'kWh in 2020' FROM v_power_per_day GROUP BY system_id; DuckDB can generate columns dynamically instead: PIVOT (FROM v_power_per_day) ON year(day) USING sum(kWh); Both produce one row per system with 2019 and 2020 values; the dynamic form avoids revising the query when years change. section 4.7

Useful variations include:

  • Pivot dates into daily columns with first(kWh) after restricting the input range. section 4.7
  • Compute several measures per pivot value, such as rounded totals and maximum daily production. section 4.7
  • Prefer static filtered aggregates when the column set is fixed or portability to databases without pivoting matters. section 4.7

How DuckDB in Action covers it

How deep it goes
Defines row-to-column transformation, demonstrates filtered aggregates and dynamic PIVOT, then extends to multiple aggregates.
Examples
Uses energy production by system and year, daily power by date, and total-versus-best-day measures.
What it assumes
Assumes grouped SQL aggregates and date expressions; begins with grouped system-and-year results before pivoting.
What you can do after
Build pivoted DuckDB reports with filtered aggregates or dynamic PIVOT, including date columns and multiple measures.
How it connects
Connects aggregation, GROUP BY, filtering, SQL transformation, and data pipelines.

Also explained in

Compare how 2 books explain pivoting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.