Learn SQL/Advanced/Window Functions/SQL Percent of Total

SQL Percent of Total

Each row's share of the whole — every percentage in the result adds up to exactly 100%.

What & Why

Dividing each row's value by the SUM OVER() of the whole group gives that row's percentage of the total — a single line of SQL, no separate query to compute the denominator.

See How It Works

BUSINESS QUESTION

Calculate each campaign's percentage of total marketing spend.

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
Watch every campaign divide by the same total spendStep 1 of 4
spend / SUM(spend) OVER () * 100
namechannelspendtotal_spendspend_share_pct
Enterprise Searchgoogle_ads60,000.00210,000.0028.57
Spring Launchgoogle_ads55,000.00210,000.0026.19
Finance Retargetinglinkedin50,000.00210,000.0023.81
Retention Webinaremail45,000.00210,000.0021.43

Enterprise Search contributes 28.57% of 210,000.

EXAMPLE QUERY
SELECT
  name,
  channel,
  spend,
  ROUND(spend::numeric / NULLIF(SUM(spend) OVER (), 0) * 100, 2) AS spend_share_pct
FROM marketing.campaigns
ORDER BY spend_share_pct DESC, name;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario