SQL Multiple Aggregates

List several aggregate functions in the same SELECT — each one is computed independently, over the same groups, in a single pass.

What & Why

Nothing stops a query from computing several different summaries at once — COUNT, SUM, AVG, MIN, and MAX can all appear side by side in the same SELECT list. Postgres computes each one independently, but all of them share the exact same groups formed by GROUP BY — so there's no cost to asking for four summaries instead of one; it's still a single pass over the data.

See How It Works

BUSINESS QUESTION

Marketing wants campaign count, total spend, and average spend together.

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,
  COUNT(*) AS campaigns,
  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
channelcampaignstotal_spendavg_spend
google_ads2115000.0057500.00
linkedin150000.0050000.00
email145000.0045000.00

Every result row summarizes one real campaign channel.

Now You Try

Practice this concept

Marketing wants campaign count, total spend, and average spend together.

Available schema
marketing

Prefix tables with marketing.table_name.

channelcampaignstotal_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