Learn SQL/Intermediate/Grouping & Aggregation/SQL GROUP BY with Aggregate Functions

SQL GROUP BY with Aggregate Functions

Any aggregate function from the Aggregate Functions series works inside a GROUP BY query — COUNT, SUM, AVG, MIN, MAX all apply per group, exactly as expected.

What & Why

Nothing new to learn here mechanically — this lesson exists to make explicit what's implicit in every example so far: every aggregate function already covered (COUNT, SUM, AVG, MIN, MAX) works exactly the same way inside a grouped query as it did company-wide. The only difference is that it's now computed once per group instead of once for the entire table.

See How It Works

BUSINESS QUESTION

Marketing wants total and average campaign spend by channel.

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
EXAMPLE QUERY
SELECT
  channel,
  SUM(spend) AS total_spend,
  ROUND(AVG(spend), 2) AS avg_spend
FROM marketing.campaigns
GROUP BY channel
ORDER BY total_spend DESC, channel;
RESULT — exact output from the displayed Queryflo rows
channeltotal_spendavg_spend
google_ads115000.0057500.00
linkedin50000.0050000.00
email45000.0045000.00

SUM and AVG run independently inside each campaign-channel group.

Now You Try

Practice this concept

Marketing wants total and average campaign spend by channel.

Available schema
marketing

Prefix tables with marketing.table_name.

channeltotal_spendavg_spend
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