Monthly Country Dashboard: Signups, Conversion, Retention, GMV, Campaign
SQL & DataModel answerLast updated
Write a single SQL query that builds a month-by-country report covering signups, 7-day conversion, day-7 retention, valid GMV, and last-touch top campaign, with dedup and UTC handling.
You are building a monthly growth report for a marketplace. You have three tables:
users(uid, created_at, country)orders(order_id, uid, amount, created_at, status)events(uid, ts, event_type, campaign)
Write one SQL query that returns one row per (month, country) with these columns:
- New users: users who signed up in that month, in that country.
- 7-day conversion rate: the share of those new users who placed a valid order within 7 days of signing up.
- 7-day retention: among user-days with activity on day D, the share that were also active on day D+7.
- GMV: the sum of order amounts, excluding refunded and canceled orders.
- Top campaign: the campaign that wins the most orders under last-touch attribution, using campaign-tagged events.
Your query must also:
- Cope with late-arriving events.
- Deduplicate events on
(uid, ts, event_type). - Keep timezones consistent across all tables.
- Explain your window-function choices (which function, partitioning, ordering, and why).
State your assumptions about metric definitions before the code. Mention where the definitions are ambiguous and how you resolved them.
Hints
Hint 1
Decide the grain and time anchor of each metric before writing SQL: signup month for new users and conversion, activity month for retention, order month for GMV and attribution.
Hint 2
Build one CTE per metric at (month, country) grain, then LEFT JOIN them all onto a spine of every (month, country) pair seen anywhere, so a country with revenue but no signups is not lost.
Hint 3
For retention, collapse events to distinct (uid, day) pairs and self-join on day + 7. For attribution, rank each order's prior tagged events by timestamp descending with ROW_NUMBER and keep rank 1, then rank campaigns per (month, country) the same way.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This task is mostly about pinning down definitions. Once each metric has an explicit grain, time anchor, and timezone, every piece is a small CTE.
| Metric | Anchor | Definition used |
|---|---|---|
| New users | Signup month (UTC) | Count of users per signup month and country |
| 7-day conversion | Signup cohort | Users with at least one valid order in [signup, signup + 7 days) divided by new users |
| 7-day retention | Month of day D | Over distinct (user, day) activity pairs, the share that also have activity on exactly D+7 |
| GMV | Order month | Sum of amount where status is not refunded or canceled |
| Top campaign | Order month | Each valid order is credited to the latest campaign-tagged event in the 7 days up to the order. The campaign with the most credited orders wins, tie-break by credited GMV, then name |
Country always comes from users, so every metric lines up on the same key.
Cross-cutting concerns
- Timezone. Convert each timestamp to UTC once, in the first CTE of each table, and never truncate raw values. If the business reports in a local zone, change the one zone literal everywhere.
- Deduplication. Use
ROW_NUMBER()partitioned by(uid, ts, event_type). The ordering inside the partition must be deterministic (here: prefer the row that carries a campaign), otherwise reruns can disagree. - Late-arriving events. Bucket by event time, not load time, so a late row lands on its true day when the job reruns. Recompute a trailing window of months on each run rather than appending. Exclude immature retention days, meaning days where D+7 plus a lateness buffer has not passed yet. If an
ingested_atcolumn exists, add a watermark on it. - Missing data. Null country becomes
'UNKNOWN'. Status matching is case-insensitive and null-safe.
Query (PostgreSQL)
WITH params AS (
SELECT (NOW() AT TIME ZONE 'UTC')::date AS today_utc,
2 AS late_buffer_days
),
u AS (
SELECT uid,
COALESCE(country, 'UNKNOWN') AS country,
created_at AT TIME ZONE 'UTC' AS signup_ts
FROM users
),
ev AS ( -- deduplicated events
SELECT uid, ts_utc, event_type, campaign
FROM (
SELECT uid, event_type, campaign,
ts AT TIME ZONE 'UTC' AS ts_utc,
ROW_NUMBER() OVER (
PARTITION BY uid, ts, event_type
ORDER BY (campaign IS NULL), campaign
) AS rn
FROM events
) x
WHERE rn = 1
),
ord AS ( -- valid orders only
SELECT order_id, uid, amount,
created_at AT TIME ZONE 'UTC' AS order_ts
FROM orders
WHERE LOWER(COALESCE(status, '')) NOT IN ('refunded','canceled','cancelled')
),
cohort_m AS (
SELECT DATE_TRUNC('month', u.signup_ts) AS month,
u.country,
COUNT(*) AS new_users,
AVG(CASE WHEN EXISTS (
SELECT 1 FROM ord o
WHERE o.uid = u.uid
AND o.order_ts >= u.signup_ts
AND o.order_ts < u.signup_ts + INTERVAL '7 days')
THEN 1.0 ELSE 0.0 END) AS conv_rate_7d
FROM u
GROUP BY 1, 2
),
daily AS (
SELECT DISTINCT uid, ts_utc::date AS d FROM ev
),
ret AS (
SELECT DATE_TRUNC('month', a.d) AS month,
u.country,
COUNT(*) AS active_days,
COUNT(b.uid) AS retained_days
FROM daily a
JOIN u USING (uid)
LEFT JOIN daily b ON b.uid = a.uid AND b.d = a.d + 7
CROSS JOIN params p
WHERE a.d + 7 + p.late_buffer_days < p.today_utc
GROUP BY 1, 2
),
gmv AS (
SELECT DATE_TRUNC('month', o.order_ts) AS month,
u.country,
SUM(o.amount) AS gmv
FROM ord o JOIN u USING (uid)
GROUP BY 1, 2
),
touch AS ( -- last touch per order
SELECT o.order_id, o.uid, o.amount, o.order_ts, e.campaign,
ROW_NUMBER() OVER (
PARTITION BY o.order_id
ORDER BY e.ts_utc DESC, e.campaign
) AS rn
FROM ord o
JOIN ev e
ON e.uid = o.uid
AND e.campaign IS NOT NULL
AND e.ts_utc <= o.order_ts
AND e.ts_utc >= o.order_ts - INTERVAL '7 days'
),
camp_agg AS (
SELECT DATE_TRUNC('month', t.order_ts) AS month,
u.country, t.campaign,
COUNT(*) AS orders_attr,
SUM(t.amount) AS gmv_attr
FROM touch t JOIN u USING (uid)
WHERE t.rn = 1
GROUP BY 1, 2, 3
),
camp_top AS (
SELECT month, country, campaign,
ROW_NUMBER() OVER (
PARTITION BY month, country
ORDER BY orders_attr DESC, gmv_attr DESC, campaign
) AS rk
FROM camp_agg
),
spine AS (
SELECT month, country FROM cohort_m
UNION SELECT month, country FROM ret
UNION SELECT month, country FROM gmv
)
SELECT s.month, s.country,
COALESCE(c.new_users, 0) AS new_users,
c.conv_rate_7d,
r.retained_days::numeric / NULLIF(r.active_days,0) AS retention_d7,
COALESCE(g.gmv, 0) AS gmv,
k.campaign AS top_campaign
FROM spine s
LEFT JOIN cohort_m c ON c.month = s.month AND c.country = s.country
LEFT JOIN ret r ON r.month = s.month AND r.country = s.country
LEFT JOIN gmv g ON g.month = s.month AND g.country = s.country
LEFT JOIN camp_top k ON k.month = s.month AND k.country = s.country AND k.rk = 1
ORDER BY s.month, s.country;
Window-function choices
- Dedup:
ROW_NUMBERpartitioned by the key.RANKwould keep ties, which defeats dedup. The tie-breakingORDER BYmakes the survivor stable. - Last touch:
ROW_NUMBERpartitioned byorder_id, ordered byts_utc DESC. Postgres has noLAST_VALUE ... IGNORE NULLS, so filtering to tagged events first and taking rank 1 is the clean equivalent. Addingcampaignto the order makes simultaneous touches deterministic. - Top campaign:
ROW_NUMBERpartitioned by(month, country). One winner per group is required, soRANK(which can return two) is the wrong tool. - Retention: no
LAG.LAGreturns the previous active day, not exactly D+7. A self-join on distinct days expresses "active again exactly 7 days later" directly.
Trade-offs and common mistakes
- Joining first, aggregating later. Joining orders to events before aggregating multiplies rows and inflates GMV. Keep one CTE per metric and join only at the end.
- Dropping rows from the spine. An inner join between metrics hides countries that have revenue but no signups in a month.
- Averaging daily rates. Retention is computed as pooled retained user-days over active user-days, not a mean of daily percentages, which would overweight quiet days.
- Immature data. Reporting retention for days whose D+7 has not happened, or has not fully arrived, understates the metric.
- Mixed timezones. Truncating
timestamptzto a month in the session zone silently shifts boundary events. - Correlated
EXISTScost. At scale, replace it with a pre-aggregated first-order-time per user (MIN(order_ts)after signup) and compare once. Partitioneventsby date and index(uid, ts). - Order amounts for users missing from
users. The inner join drops them. Decide whether to bucket them as'UNKNOWN'and say so.
Complexity
Each CTE is a scan plus a hash or sort aggregate. The heaviest steps are the order-to-event join (bounded by the 7-day lookback and uid index) and the retention self-join (one row per active user-day). Both are roughly linear in the number of events with proper indexing.