SQL AVG OVER

SQL AVG OVER helps analysts calculate a windowed average while preserving every detail row.

What & Why

The AVG OVER pattern is used to calculate a windowed average while preserving every detail row. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Marketing wants each campaign compared with average spend in its 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
  id AS campaign_id,
  channel,
  spend,
  ROUND(AVG(spend) OVER (PARTITION BY channel), 2) AS channel_avg_spend
FROM marketing.campaigns
ORDER BY channel, campaign_id;
RESULT — channel average beside campaigns
campaign_idchannelspendchannel_avg_spend
2email45000.0045000.00
1google_ads55000.0057500.00
4google_ads60000.0057500.00
3linkedin50000.0050000.00

The google_ads partition contains two campaigns; the other partitions contain one.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario