Learn SQL/Advanced/Window Functions/SQL Window Function vs GROUP BY

SQL Window Function vs GROUP BY

Same aggregate math — one keeps every row, the other collapses them.

What & Why

GROUP BY and a window function can compute the exact same average, sum, or count — the only difference is whether the individual rows survive in the output.

See How It Works

BUSINESS QUESTION

Compare campaign-level channel counts with a collapsed channel summary.

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
Compare preserved detail with grouped result grainStep 1 of 2
COUNT(*) OVER (PARTITION BY channel)
campaign_idnamechannelchannel_campaigns
2Retention Webinaremail1
1Spring Launchgoogle_ads2
4Enterprise Searchgoogle_ads2
3Finance Retargetinglinkedin1

The window keeps four campaign rows and adds each channel's count beside them.

EXAMPLE QUERY
-- Preserve every campaign row
SELECT
  id AS campaign_id,
  name,
  channel,
  COUNT(*) OVER (PARTITION BY channel) AS channel_campaigns
FROM marketing.campaigns
ORDER BY channel, campaign_id;

-- Collapse to one row per channel
SELECT
  channel,
  COUNT(*) AS channel_campaigns
FROM marketing.campaigns
GROUP BY channel
ORDER BY channel;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario