Campaign Profit by Segment and Gala Seat Filling in SQL
SQL & DataModel answerLast updated
Build per-campaign, per-segment fundraising metrics for August 2025 with fan-out-safe joins and cost allocation, pick the more profitable campaign, then choose extra gala invitees.
A charity runs several fundraising campaigns, and you need to report on how profitable each one was. You are given four tables.
Schema
donors(donor_id INT PRIMARY KEY, segment CHAR(1))campaigns(campaign_id INT PRIMARY KEY, name VARCHAR, channel VARCHAR, fixed_cost DECIMAL, variable_cost_per_reach DECIMAL)contacts(contact_id INT PRIMARY KEY, donor_id INT, campaign_id INT, reached_dt DATE)donations(donation_id INT PRIMARY KEY, donor_id INT, campaign_id INT, amount DECIMAL, donation_dt DATE)
Sample data
donors
| donor_id | segment |
|---|---|
| 1 | H |
| 2 | L |
| 3 | L |
| 4 | H |
| 5 | L |
campaigns
| campaign_id | name | channel | fixed_cost | variable_cost_per_reach |
|---|---|---|---|---|
| 10 | Gala Fall | gala | 20000 | 100 |
| 20 | Email Sept | online | 8000 | 1 |
contacts
| contact_id | donor_id | campaign_id | reached_dt |
|---|---|---|---|
| 101 | 1 | 10 | 2025-08-15 |
| 102 | 2 | 10 | 2025-08-15 |
| 103 | 4 | 10 | 2025-08-15 |
| 201 | 3 | 20 | 2025-08-31 |
| 202 | 5 | 20 | 2025-08-31 |
donations
| donation_id | donor_id | campaign_id | amount | donation_dt |
|---|---|---|---|---|
| 301 | 1 | 10 | 1000 | 2025-08-16 |
| 302 | 2 | 10 | 250 | 2025-08-16 |
| 401 | 3 | 20 | 50 | 2025-09-01 |
| 402 | 5 | 20 | 40 | 2025-09-01 |
Tasks
- For every
campaign_idand donorsegment, report these metrics for August 2025:total_reached,donors(distinct donors who gave),conversion_rate,gross_donations,variable_cost,fixed_cost, andnet_revenue = gross_donations - (fixed_cost + variable_cost). - Return a single row that shows which of the gala campaign and the online campaign has the higher
net_revenue. - Write a query that recommends the top 10 extra donors to invite to the gala. Rank candidates by their donation total over the last 12 months, and exclude anyone already contacted for the gala.
Rules and assumptions
- For the gala, variable cost is charged per attendee, which means per contact row. Apply the same per-contact-row rule to every campaign.
- Gala capacity is 100. Campaign 10 currently has fewer than 100 contact rows, so only the remaining seats can be filled.
- A table
donations_hist(donor_id, amount, donation_dt)holds historical giving for Task 3. - Some inputs are ambiguous, for example what "August" means for a donation made the day after a contact. State the interpretation you choose and explain why.
Expected: the SQL for all three tasks, the result on the sample data, and a short explanation of the pitfalls you avoided.
Hints
Hint 1
Joining contacts straight to donations repeats each gift once per contact row and inflates revenue. Collapse each fact table to one row per (campaign_id, donor_id) before joining.
Hint 2
Fixed cost belongs to the whole campaign, but the output has one row per segment. Split it across segments in proportion to how many donors each segment reached, so the pieces add back to the campaign total.
Hint 3
One online contact is on 2025-08-31 and its gifts arrive on 2025-09-01. Think about defining the month by when the donor was reached, not when they gave. For Task 3, use NOT EXISTS instead of NOT IN and cap the result at the seats still open.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is three queries, and each has one main trap.
- Fan-out.
contactsanddonationsare both many-to-one against a donor. Joining them directly multiplies every gift by the number of contact rows. Aggregate each side to(campaign_id, donor_id)first, then join. - Grain mismatch.
fixed_costis stored per campaign, but the report is per campaign and segment. Copying it onto every segment row double-counts it. Allocate it by each segment's share of reached donors, so the segments sum back to the true cost. - Defining "August". The online campaign reached people on 31 Aug, and their gifts landed on 1 Sep. Filtering donations by date would erase all online revenue. I define August as a reach cohort: take contacts made in August, then count that campaign's gifts from those donors on or after their first reach date. I would say this out loud in an interview, since a different reading changes the numbers.
Other assumptions:
total_reachedis the count of distinct donors reached.variable_costis contact rows timesvariable_cost_per_reach.- The dialect is PostgreSQL.
Task 1: Segment-level metrics
CREATE VIEW campaign_segment_metrics AS
WITH win AS (
SELECT DATE '2025-08-01' AS d_from, DATE '2025-09-01' AS d_to
),
reached AS ( -- one row per campaign + donor reached in August
SELECT c.campaign_id, c.donor_id, d.segment,
COUNT(*) AS contact_rows,
MIN(c.reached_dt) AS first_reach
FROM contacts c
JOIN donors d ON d.donor_id = c.donor_id
CROSS JOIN win w
WHERE c.reached_dt >= w.d_from AND c.reached_dt < w.d_to
GROUP BY c.campaign_id, c.donor_id, d.segment
),
given AS ( -- one row per campaign + donor who gave after reach
SELECT r.campaign_id, r.donor_id, SUM(x.amount) AS amount
FROM reached r
JOIN donations x
ON x.campaign_id = r.campaign_id
AND x.donor_id = r.donor_id
AND x.donation_dt >= r.first_reach
GROUP BY r.campaign_id, r.donor_id
),
by_seg AS (
SELECT r.campaign_id, r.segment,
COUNT(*) AS total_reached,
SUM(r.contact_rows) AS contact_rows,
COUNT(g.donor_id) AS donors,
COALESCE(SUM(g.amount), 0) AS gross_donations
FROM reached r
LEFT JOIN given g
ON g.campaign_id = r.campaign_id AND g.donor_id = r.donor_id
GROUP BY r.campaign_id, r.segment
),
costed AS (
SELECT s.*, ca.name, ca.channel,
s.contact_rows * ca.variable_cost_per_reach AS variable_cost,
ca.fixed_cost * s.total_reached::numeric
/ SUM(s.total_reached) OVER (PARTITION BY s.campaign_id) AS fixed_cost
FROM by_seg s
JOIN campaigns ca USING (campaign_id)
)
SELECT campaign_id, name, channel, segment, total_reached, donors,
donors::numeric / NULLIF(total_reached, 0) AS conversion_rate,
gross_donations, variable_cost, fixed_cost,
gross_donations - (fixed_cost + variable_cost) AS net_revenue
FROM costed;
Keep values unrounded in the view and round only when displaying, so segment figures still add up exactly in Task 2.
Result on the sample
| campaign | segment | reached | donors | conv. rate | gross | variable | fixed | net |
|---|---|---|---|---|---|---|---|---|
| 10 | H | 2 | 1 | 0.5000 | 1000 | 200 | 13333.33 | -12533.33 |
| 10 | L | 1 | 1 | 1.0000 | 250 | 100 | 6666.67 | -6516.67 |
| 20 | L | 2 | 2 | 1.0000 | 90 | 2 | 8000.00 | -7912.00 |
Task 2: Gala vs online in one row
Because the allocation is linear, summing segment rows recovers the campaign totals.
SELECT channel, campaign_id, name,
SUM(gross_donations) AS gross_donations,
SUM(variable_cost) + SUM(fixed_cost) AS total_cost,
SUM(net_revenue) AS net_revenue
FROM campaign_segment_metrics
WHERE channel IN ('gala', 'online')
GROUP BY channel, campaign_id, name
ORDER BY net_revenue DESC, campaign_id
LIMIT 1;
Online (campaign 20) wins with net -7,912. The gala gets 1,250 - 20,000 - 300 = -19,050. "Higher" means less negative. Both campaigns lose money, which is worth flagging as a finding. If you filtered gifts to August only, online would drop to -8,002. The winner is the same, but the figure changes, and that is why the cohort definition matters. If a channel can have several campaigns, decide whether you are comparing campaigns (as above) or channel totals (group by channel only).
Task 3: Extra gala invitees
WITH seats AS (
SELECT GREATEST(100 - COUNT(*), 0) AS open_seats
FROM contacts
WHERE campaign_id = 10
),
recent AS (
SELECT h.donor_id, SUM(h.amount) AS last_12m_amount
FROM donations_hist h
WHERE h.donation_dt > DATE '2025-08-31' - INTERVAL '12 months'
AND h.donation_dt <= DATE '2025-08-31'
AND NOT EXISTS (
SELECT 1 FROM contacts c
WHERE c.campaign_id = 10 AND c.donor_id = h.donor_id)
GROUP BY h.donor_id
),
ranked AS (
SELECT recent.*,
ROW_NUMBER() OVER (ORDER BY last_12m_amount DESC, donor_id) AS rn
FROM recent
)
SELECT r.donor_id, d.segment, r.last_12m_amount
FROM ranked r
CROSS JOIN seats s
LEFT JOIN donors d ON d.donor_id = r.donor_id
WHERE r.rn <= LEAST(10, s.open_seats)
ORDER BY r.rn;
Design choices:
NOT EXISTSoverNOT IN. A single NULLdonor_idin the subquery makesNOT INreturn nothing.LEAST(10, open_seats). This keeps the list within capacity when fewer than 10 seats remain. It also avoids relying on a subquery insideLIMIT, which not every dialect allows.- Anchor date. I fixed it at 2025-08-31 to match the reporting month. In production, parameterize it or use
CURRENT_DATE. - Deterministic ties. Adding
donor_idto the ordering makes equal totals reproducible. - Aggregate before ranking. Donors can have many historical gifts, so sum per donor first.
Complexity
Each query scans the fact tables once, with hash aggregations and a join on (campaign_id, donor_id). Cost is roughly O(N log N) from the grouping and sorting. Indexes on contacts(campaign_id, reached_dt) and donations(campaign_id, donor_id, donation_dt) help.
Common mistakes
- Joining contacts to donations before aggregating, which inflates revenue.
- Repeating the full fixed cost on every segment row.
- Filtering by donation date and silently dropping the 1 Sep gifts.
- Counting contact rows instead of distinct donors in the conversion rate.
- Dividing without
NULLIF, or using integer division for the rate. - Using
NOT INagainst a nullable column. - Ignoring that fewer than 10 seats may be left.