Have you ever needed to sum, count, or average only the rows that meet a condition? For example, counting the rows from the last month, or summing the sales in one category.
If you've used Excel's COUNTIF or SUMIF, the idea is the same in SQL.
Conditional aggregation lets you aggregate values only when they meet a condition.
The basic pattern is to wrap a CASE statement inside an aggregate function. The CASE picks out the rows you want, and the aggregate works on those.
(A CASE is used here as an IF statement for SQL languages/databases that don't support IF or IFF functions. If your platform supports IF or IFF, you can use these instead)
Aggregate
-- Sum profits only for 'Fiction Books' and 'Non-Fiction Books'
SUM(
CASE
WHEN [Category] IN ( 'Fiction Books', 'Non-Fiction Books' )
THEN profit
END
) For example, the above SQL wraps a case statement looking for 'Fiction Books' and 'Non-Fiction Books' and sums only these records.

Other common usecases of conditional aggregations finding outliers (e.g. Count months where profit > 20,000), filtering to a specific date or date range (e.g. Sum up profit in the last 30 days) and more!
Pivot via Conditional Aggregations
Pivoting is where you shift data from rows to columns, or convert a 'tall' table to a 'wide' table.
We won't go over what pivots are in depth here, but check out this guide on pivoting and unpivoting if you want to know more.
For SQL databases/languages that don't support a 'Pivot' function, such as MySQL, SQLite and MariaDB, pivoting is done via conditional aggregations.
-- Create a column for January's Sales
SUM(
CASE
WHEN month = 'Jan'
THEN profit
END
) AS Jan_Profit,
-- Create a column for February's Sales
SUM(
CASE
WHEN month = 'Feb'
THEN profit
END
) AS Feb_Profit
(...)For this example, conditional aggregations are used to extract and sum the numbers for each month before putting them into columns.


