Performance marketing wants cost per signup by campaign, but only for campaigns that actually spent money.
Using a CTE, aggregate campaign_spend to one row per campaign_name (total spend and total signups), then return campaign_name, total_spend, total_signups and cost_per_signup (total spend divided by total signups, rounded to 2 decimals) for campaigns whose total spend is above 50000. Skip campaigns with zero signups.
Sample data
Table: campaign_spend
15 row(s) · showing first 8
| row_idINT | campaign_nameTEXT | spend_dateDATE | spendNUMERIC(10,2) | signupsINT |
|---|---|---|---|---|
| 1 | Search Brand | 2026-01-05 | 22000.00 | 140 |
| 2 | Search Brand | 2026-01-12 | 26500.00 | 165 |
| 3 | Search Brand | 2026-01-19 | 18000.00 | 96 |
| 4 | Social Retarget | 2026-01-06 | 12000.00 | 45 |
| 5 | Social Retarget | 2026-01-13 | 15500.00 | 61 |
| 6 | Social Retarget | 2026-01-20 | 14200.00 | 52 |
| 7 | YouTube Preroll | 2026-01-07 | 31000.00 | 88 |
| 8 | YouTube Preroll | 2026-01-14 | 28500.00 | 74 |
campaign_spend
- row_idINT
- campaign_nameTEXT
- spend_dateDATE
- spendNUMERIC(10,2)
- signupsINT
- Step 1: Define a CTE named `campaign_totals` that rolls the daily rows up to one row per campaign with `SUM(spend)` and `SUM(signups)`.
- Step 2: A CTE lets the outer query reference those aggregates by name, so the division stays readable instead of repeating two `SUM()` calls.
- Step 3: In the outer query keep only meaningful campaigns: `total_spend > 50000` and `total_signups > 0` — the second condition also protects against division by zero.
- Step 4: Compute efficiency as `total_spend / total_signups` and round to 2 decimals.
- Step 5: Project the campaign, its totals and the derived `cost_per_signup`.
WITH campaign_totals AS (
SELECT campaign_name,
SUM(spend) AS total_spend,
SUM(signups) AS total_signups
FROM campaign_spend
GROUP BY campaign_name
)
SELECT campaign_name,
total_spend,
total_signups,
ROUND(total_spend / total_signups, 2) AS cost_per_signup
FROM campaign_totals
WHERE total_spend > 50000
AND total_signups > 0;Learn the concept first
Stuck on CTEs? These free SQL lessons teach it step by step.
More CTEs questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program