Highest Spender in the Company's First Decade
SQL & DataModel answerLast updated
Identify which user spent the most money during the initial ten-year period starting from the company's very first transaction.
You have two tables at your disposal: transactions and users.
The transactions table schema:
transaction_id(integer)user_id(integer)amount(float)transaction_date(date)
The users table schema:
user_id(integer)signup_date(date)
Your task is to determine which user accumulated the largest total spending during the company's first decade of operation. The company's inception date is defined as the earliest transaction date found in the transactions table. When multiple users are tied with identical top spending amounts, your query should return all of them.
Example:
Given these transactions:
| transaction_id | user_id | amount | transaction_date |
|---|---|---|---|
| 1 | 101 | 500 | 2010-01-05 |
| 2 | 102 | 800 | 2010-06-01 |
| 3 | 101 | 400 | 2015-02-01 |
| 4 | 103 | 2000 | 2022-01-01 |
Expected output:
| user_id | total_spent |
|---|---|
| 101 | 900 |
The company began on 2010-01-05, so the ten-year window closes on 2020-01-05. Transaction 4 falls outside this range and is excluded. User 101's total is 900 (500 + 400), which exceeds user 102's 800.
Hints
Hint 1
First determine the company's founding date by finding the minimum transaction date across all records.
Hint 2
After establishing the time window boundaries, filter transactions to include only those within the first ten years, then aggregate spending per user.
Hint 3
When selecting the top spender, use RANK() rather than LIMIT 1 to ensure all tied users are included in your result.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem breaks down into three logical phases:
Phase 1: Establish the time window
Compute the earliest transaction date in the dataset—this marks day zero for the company. The decade window spans from this start date up to (but not including) the same date ten years later.
Phase 2: Filter and aggregate
Retain only transactions falling within the window, then sum each user's spending by grouping on user_id.
Phase 3: Identify the maximum while preserving ties
Use RANK() to order users by their total spending in descending order. All users receiving rank 1 are top spenders and should appear in the output. Avoid ROW_NUMBER() or LIMIT 1, as both would arbitrarily discard tied users.
A clarification worth raising: should a transaction occurring exactly on the tenth anniversary be included? The phrase "first 10 years" typically implies the half-open interval [start, start + 10 years), excluding the anniversary date itself. Always state your assumption.
SQL Solution (PostgreSQL)
WITH company_start AS (
SELECT MIN(transaction_date) AS founding_date
FROM transactions
),
window_totals AS (
SELECT
t.user_id,
SUM(t.amount) AS total_spent
FROM transactions t
CROSS JOIN company_start cs
WHERE t.transaction_date >= cs.founding_date
AND t.transaction_date < cs.founding_date + INTERVAL '10 years'
GROUP BY t.user_id
),
ranked_spenders AS (
SELECT
user_id,
total_spent,
RANK() OVER (ORDER BY total_spent DESC) AS spending_rank
FROM window_totals
)
SELECT user_id, total_spent
FROM ranked_spenders
WHERE spending_rank = 1
ORDER BY user_id;
How it works:
company_startproduces a single-row result containing the earliest transaction dateCROSS JOINattaches this founding date to every transaction row (efficient because the CTE has exactly one row)- The
WHEREclause filters to the half-open decade interval SUM(t.amount) GROUP BY t.user_idcomputes per-user totals for in-window transactions onlyRANK()assigns rank 1 to every user tied at the maximum;DENSE_RANK()works equally well here- The final filter keeps only rank-1 users
Dialect variations for date arithmetic:
- MySQL:
DATE_ADD(founding_date, INTERVAL 10 YEAR) - SQL Server / Snowflake:
DATEADD(year, 10, founding_date)
Python (pandas) Solution
import pandas as pd
def find_top_spender(transactions: pd.DataFrame,
users: pd.DataFrame) -> pd.DataFrame:
if transactions.empty:
return pd.DataFrame({
"user_id": pd.Series(dtype="int64"),
"total_spent": pd.Series(dtype="float64")
})
df = transactions.copy()
df["transaction_date"] = pd.to_datetime(df["transaction_date"])
founding_date = df["transaction_date"].min()
window_end = founding_date + pd.DateOffset(years=10)
in_window = df[
(df["transaction_date"] >= founding_date) &
(df["transaction_date"] < window_end)
]
user_totals = (
in_window.groupby("user_id", as_index=False)["amount"]
.sum()
.rename(columns={"amount": "total_spent"})
)
max_spending = user_totals["total_spent"].max()
top_spenders = user_totals[user_totals["total_spent"] == max_spending]
return top_spenders.sort_values("user_id").reset_index(drop=True)
This mirrors the SQL logic: compute the founding date, apply a boolean mask to filter the window, aggregate by user, then select all rows matching the maximum total.
Complexity
Given n transactions and u distinct users within the window:
- Time: O(n) to scan for the minimum date and filter transactions, O(n) for hash-based aggregation, O(u log u) to rank users (or O(u) if you compute the max and filter directly)
- Space: O(u) to store per-user totals
Edge Cases and Considerations
- Empty table: If no transactions exist,
MINreturnsNULL, the filter passes nothing, and the result is correctly empty - Ties:
RANK()ensures all tied top spenders appear - NULL amounts:
SUMignores them; a user with only NULL amounts gets a NULL total, which sorts last underDESC(addNULLS LASTexplicitly to be safe) - Floating-point precision: Since
amountis float, two sums might differ by tiny rounding errors. In production, represent money asNUMERIC(precision, 2)or integer cents - Negative amounts (refunds): These reduce the total. Confirm the business rule
- Leap day edge case: Starting on 2012-02-29 and adding ten years yields 2022-02-28 in most systems. Mention this if asked
- Boundary inclusion: If the interviewer expects the tenth anniversary to be included, change
<to<=or useBETWEEN
Common Mistakes
- Using
LIMIT 1orROW_NUMBER(), which silently drops tied users - Filtering after grouping instead of before, which inflates totals
- Forgetting the half-open interval and including transactions from year eleven onward
- Assuming the company start date is known externally rather than deriving it from the data
Extensions
Exclude users who joined after the window opened:
Join transactions to users and add WHERE u.signup_date <= cs.founding_date. Clarify whether "after the window started" means after the start date or after the end date.
Best spending in any rolling 10-year span per user:
Use a range window function:
SUM(amount) OVER (
PARTITION BY user_id
ORDER BY transaction_date
RANGE BETWEEN CURRENT ROW
AND INTERVAL '10 years' FOLLOWING
)
Then take each user's maximum and rank. In Python, sort each user's transactions and apply a two-pointer sliding window.
Scale to billions of rows:
Partition or cluster the table by transaction_date so the engine can skip irrelevant partitions. Use columnar storage (Redshift, BigQuery, Snowflake) to read only the columns needed. If the window is static, materialize filtered totals in a summary table and refresh incrementally.