User Spend Tiers in Pandas and Daily Platform Conversion in SQL
SQL & DataModel answerLast updated
Build a per-user revenue and distinct-purchase table with tiers in Pandas, then write SQL for daily purchase-to-click conversion by platform over the last 30 days.
Context
You maintain the event pipeline for a consumer mobile and web app. Every interaction is logged in an events table, and you need to produce a periodic report on spending and engagement.
events
| user_id | event_time | event_type | platform | revenue |
|---|---|---|---|---|
| 101 | 2024-04-01 12:01:00 | click | iOS | 0.00 |
| 101 | 2024-04-01 12:02:10 | purchase | iOS | 4.99 |
| 202 | 2024-04-01 13:05:33 | view | Android | 0.00 |
| 303 | 2024-04-01 14:20:05 | click | Web | 0.00 |
| 202 | 2024-04-01 14:45:00 | purchase | Android | 9.99 |
Tasks
-
Pandas user summary. From the events DataFrame, build one row per user containing:
- total revenue
- the number of distinct purchases
-
Spend tiers. Add a
tiercolumn usingapplywith alambdaon total revenue:0: no spend0-5: spend above 0 and up to 55+: spend above 5
Also show a dictionary-based mapping (for example, tier to a display label or sort rank).
-
SQL conversion rate. Write a query returning, for each platform and each day in the last 30 days, the conversion rate
purchases / clicks.
What to cover in your answer
- State your assumptions about what counts as a "distinct purchase" (there is no event ID column) and what "last 30 days" means.
- Give the Pandas code, the SQL, and the expected output for the sample rows.
- Explain how you handle days or platforms with zero clicks, duplicate events, and floating-point revenue.
- Give the time and space complexity.
Hints
Hint 1
In one groupby you can sum revenue and also count distinct purchases, if you first create a column that holds the timestamp only on purchase rows and is missing elsewhere (nunique skips missing values).
Hint 2
Tier boundaries are easiest to get right by testing the zero case first, then 'at most 5', then everything else. A plain dict can then turn the tier string into a rank or label via map.
Hint 3
For the SQL, count clicks and purchases in the same scan with conditional aggregation (CASE or FILTER), group by platform and the date part of event_time, and protect the division with NULLIF and a cast to a decimal type.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Three things are being tested: a clean groupby, row-wise classification logic, and a SQL ratio that does not break on edge cases. I would state assumptions first, then code.
Assumptions to state
- Total revenue is the sum of
revenueper user. Non-purchase rows carry0.00, so summing all rows is safe. Restricting to purchase rows makes the intent explicit and protects against bad data. - Distinct purchase has no event ID to rely on, so I define it as a unique
(user_id, event_time)amongpurchaserows. Retries in a pipeline often emit duplicates. With a real event ID I would count unique IDs instead. - Tiers:
0means revenue is exactly 0,0-5means more than 0 and at most 5, and5+means more than 5. - Conversion rate is purchases divided by clicks, per platform per calendar day.
- Last 30 days means today plus the previous 29 days. The alternative, 30 full days that exclude today's partial day, is also reasonable. I would pick one and say so.
- Users with no events in the reporting window do not appear. A full roster would need a join to a users table.
Part 1: Pandas
The trick is a helper column holding the timestamp only on purchase rows. nunique ignores missing values, so a single groupby yields both aggregates, with no second pass and no merge.
import pandas as pd
TIER_RANK = {"0": 0, "0-5": 1, "5+": 2}
TIER_LABEL = {"0": "no spend", "0-5": "low spender", "5+": "high spender"}
def build_user_summary(events: pd.DataFrame) -> pd.DataFrame:
df = events.copy()
df["event_time"] = pd.to_datetime(df["event_time"])
is_purchase = df["event_type"].eq("purchase")
df["purchase_time"] = df["event_time"].where(is_purchase) # NaT for non-purchases
df["purchase_rev"] = df["revenue"].where(is_purchase, 0.0)
summary = (
df.groupby("user_id", as_index=False)
.agg(total_revenue=("purchase_rev", "sum"),
purchase_count=("purchase_time", "nunique"))
)
summary["total_revenue"] = summary["total_revenue"].round(2)
summary["tier"] = summary["total_revenue"].apply(
lambda r: "0" if r <= 0 else ("0-5" if r <= 5 else "5+")
)
summary["tier_rank"] = summary["tier"].map(TIER_RANK)
summary["tier_label"] = summary["tier"].map(TIER_LABEL)
return summary.sort_values(["tier_rank", "total_revenue"],
ascending=False, ignore_index=True)
Expected output on the sample:
| user_id | total_revenue | purchase_count | tier |
|---|---|---|---|
| 202 | 9.99 | 1 | 5+ |
| 101 | 4.99 | 1 | 0-5 |
| 303 | 0.00 | 0 | 0 |
User 303 still appears with zero revenue because every event row takes part in the groupby, even though none of them is a purchase.
Vectorized alternative. apply runs a Python-level loop over users. At scale, pd.cut(summary.total_revenue, [-float("inf"), 0, 5, float("inf")], labels=["0","0-5","5+"]) is much faster. The bins are right-inclusive, which matches the tier rules. I would use apply here because the task asks for it, and mention pd.cut as the production choice.
Part 2: SQL (Postgres dialect)
Use conditional aggregation so that clicks and purchases are counted in a single scan.
SELECT
platform,
CAST(event_time AS DATE) AS event_date,
COUNT(*) FILTER (WHERE event_type = 'purchase') AS purchases,
COUNT(*) FILTER (WHERE event_type = 'click') AS clicks,
COUNT(*) FILTER (WHERE event_type = 'purchase')::numeric
/ NULLIF(COUNT(*) FILTER (WHERE event_type = 'click'), 0) AS conversion_rate
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '29 days'
AND event_time < CURRENT_DATE + INTERVAL '1 day'
GROUP BY platform, CAST(event_time AS DATE)
ORDER BY event_date, platform;
In engines without FILTER, use SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END).
Result for 2024-04-01 on the sample:
| platform | purchases | clicks | conversion_rate |
|---|---|---|---|
| iOS | 1 | 1 | 1.0 |
| Android | 1 | 0 | NULL |
| Web | 0 | 1 | 0.0 |
Android shows a purchase with no click. That is realistic (deep links, reorders), and NULL is the honest answer rather than an error or infinity.
Why this is correct
- The
WHEREclause filters rows before aggregation, so only events in the window contribute. - Each output row corresponds to exactly one
(platform, day)group, and each conditional count only sees its own event type. NULLIF(..., 0)prevents division by zero, and the::numericcast prevents integer division from silently returning 0.- In Pandas,
nuniqueon the purchase-only column counts each(user, timestamp)purchase once, even if the pipeline duplicated it.
Complexity
- Pandas: O(n) time for the hash groupby over n events, plus O(u) for the tier step over u users. Space is O(u).
- SQL: one scan of the filtered rows and a hash aggregate, so O(n) time and O(p · d) space for p platforms and at most 30 days. Partitioning or indexing on
event_timemakes the date filter cheap.
Edge cases and trade-offs
- Duplicate events: Pandas handles them through
nunique. In SQL, useCOUNT(DISTINCT user_id || event_time)or an event ID if duplicates matter. Say whether the rate should count raw or deduplicated events. - Zero clicks: return
NULL, not 0, so that "no data" is not confused with "no conversion". - Ratio above 1: possible when purchases exceed clicks. Report it as is rather than clamping.
- Missing days: days with no events are absent. For a dense series, generate dates with
generate_series, cross join with platforms, andLEFT JOINthe aggregates. - Floating-point revenue: sums like
4.99 + 0.01may not equal exactly5.00. Round before tiering, or store money as integer cents orDECIMAL. - Time zones: "daily" depends on the zone. Convert
event_timeto the business time zone before casting to a date. - Weekly scope: for a weekly report, filter to the target week first, or add the week (
event_time.dt.to_period("W")) as a second groupby key.
Common mistakes
- Using
countinstead ofnunique, which counts rows and duplicates. - Dropping non-purchasers by filtering to purchases before the groupby, which loses users such as 303.
- Off-by-one tier boundaries, for example putting exactly 5.00 in
5+. - Integer division in SQL.
- Using
BETWEENwith a timestamp upper bound of today's date, which cuts off most of today's events.