KatInterview

User Spend Tiers in Pandas and Daily Platform Conversion in SQL

SQL & DataModel answer
MediumModel answerSQL & Datapandasgroupbysql

Last 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_idevent_timeevent_typeplatformrevenue
1012024-04-01 12:01:00clickiOS0.00
1012024-04-01 12:02:10purchaseiOS4.99
2022024-04-01 13:05:33viewAndroid0.00
3032024-04-01 14:20:05clickWeb0.00
2022024-04-01 14:45:00purchaseAndroid9.99

Tasks

  1. Pandas user summary. From the events DataFrame, build one row per user containing:

    • total revenue
    • the number of distinct purchases
  2. Spend tiers. Add a tier column using apply with a lambda on total revenue:

    • 0: no spend
    • 0-5: spend above 0 and up to 5
    • 5+: spend above 5

    Also show a dictionary-based mapping (for example, tier to a display label or sort rank).

  3. 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.