liveBook · Manning

Filtered aggregate

As explained in DuckDB in Action

A filtered aggregate is an aggregate expression that incorporates only rows satisfying a specified filter condition.

A filtered aggregate calculates an aggregate over only rows matching a condition. Multiple filtered aggregates can turn grouped power data into a fixed-column report, such as yearly production per system. section 4.7

Yearly power production by system

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; The result keeps systems as rows and produces separate 2019 and 2020 production columns. section 4.7

Listing 4.25 Statically pivoting a result by applying a filter to all aggregates selected
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;

Inspect the complete SQL listing for a static pivot using filtered sum aggregates. section 4.7

How DuckDB in Action covers it

How deep it goes
Defines FILTER (WHERE ...) and demonstrates multiple aggregates, but defers dynamic columns to DuckDB’s PIVOT clause.
Examples
Demonstrates yearly kWh totals for systems 10, 34, and 1200 using 2019 and 2020 columns.
What you can do after
Apply it via SQL to produce static pivot reports with one aggregate column per condition.
How it connects
Connects filtered aggregates with aggregation, GROUP BY, pivoting, and DuckDB’s PIVOT clause.

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.