Learn SQL/Intermediate/Conditional Logic/SQL CASE with Aggregates

SQL CASE with Aggregates

Wrap a CASE expression inside an aggregate function to summarize only the rows matching a condition — the exact technique the Grouping series introduced as conditional aggregation.

What & Why

This is the same conditional aggregation pattern from the Grouping & Aggregation series, revisited here from the CASE side rather than the aggregate-function side. The mechanics are identical: SUM(CASE WHEN condition THEN column ELSE 0 END) sums only the rows where condition is true, treating every other row as a contributed zero.

See How It Works

BUSINESS QUESTION

Marketing wants recipients and clicks for active campaigns only.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
idcampaign_idsent_atrecipientsopensclicksunsubscribesbounces
20112024-01-20 15:00:00+001200540180924
20222024-02-15 16:30:00+0080042096512
20332024-03-18 13:00:00+0015006102251431
20442024-04-08 14:00:00+0000000
EXAMPLE QUERY
SELECT
  c.channel,
  SUM(CASE WHEN c.status = 'active' THEN e.recipients ELSE 0 END) AS active_recipients,
  SUM(CASE WHEN c.status = 'active' THEN e.clicks ELSE 0 END) AS active_clicks
FROM marketing.campaigns c
JOIN marketing.email_sends e ON e.campaign_id = c.id
GROUP BY c.channel
ORDER BY active_recipients DESC, c.channel;
RESULT — exact output from the displayed Queryflo rows
channelactive_recipientsactive_clicks
linkedin1500225
google_ads1200180
email80096

Each conditional SUM uses the real active campaign and email-send rows.

Now You Try

Practice this concept

Marketing wants recipients and clicks for active campaigns only.

Available schema
marketing

Prefix tables with marketing.table_name.

channelactive_recipientsactive_clicks
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario