Learn SQL/Intermediate/Grouping & Aggregation/SQL Aggregate Calculations

SQL Aggregate Calculations

Aggregate results are just numbers — ordinary arithmetic works directly on them, letting a query compute derived business metrics in one step.

What & Why

Once an aggregate function produces a value, it behaves exactly like any other number in the query — it can be added, multiplied, divided, or combined with other aggregates using ordinary arithmetic operators, right there in the same SELECT list. This is how a single query ends up computing a genuinely derived business metric, not just a raw sum or average.

See How It Works

BUSINESS QUESTION

Marketing wants the conversion rate for leads from each source.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
EXAMPLE QUERY
SELECT
  source,
  COUNT(*) AS leads,
  COUNT(*) FILTER (WHERE converted_at IS NOT NULL) AS conversions,
  ROUND(100.0 * COUNT(*) FILTER (WHERE converted_at IS NOT NULL) / NULLIF(COUNT(*), 0), 2) AS conversion_rate
FROM marketing.leads
GROUP BY source
ORDER BY conversion_rate DESC NULLS LAST, source;
RESULT — exact output from the displayed Queryflo rows
sourceleadsconversionsconversion_rate
linkedin11100.00
google_ads2150.00
email100.00

The conversion numerator and denominator come from the same source group.

Now You Try

Practice this concept

Marketing wants the conversion rate for leads from each source.

Available schema
marketing

Prefix tables with marketing.table_name.

sourceleadsconversionsconversion_rate
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario