SQL Window Functions, Join Types, and Python Aggregation
SQL & DataModel answerLast updated
Demonstrate SQL window functions, join semantics, ranking functions, string aggregation, and Python dict-based accumulation over transactional row data.
Transaction Data: SQL and Python Manipulation
You have a transactions table with the following structure and sample data:
| transaction_id | user_id | merchant | amount | currency | transaction_ts |
|---|---|---|---|---|---|
| 1001 | 17 | Walmart | 45.80 | USD | 2023-07-12 14:02:08 |
| 1002 | 22 | Target | 23.15 | USD | 2023-07-12 15:10:44 |
| 1003 | 17 | Walmart | 120.99 | USD | 2023-07-13 09:21:11 |
| 1004 | 30 | eBay | 65.00 | USD | 2023-07-13 10:05:33 |
Answer all six parts below. Show runnable SQL and Python where asked.
Part 1 — Window functions conceptually
What is a window function? How does it differ from GROUP BY? List at least four practical use cases.
Part 2 — Join types
Describe the behaviour of INNER, LEFT, RIGHT, FULL OUTER, and CROSS joins. Mention at least one common pitfall for each of the outer join types.
Part 3 — RANK vs DENSE_RANK
Explain the difference between RANK(), DENSE_RANK(), and ROW_NUMBER(). Given a tied data set, show what each function produces and when you would choose each one.
Part 4 — Total spend per merchant Write a query that returns total GMV (gross merchandise value) and transaction count per merchant, in descending order of GMV. Note any currency handling concern.
Part 5 — Merchants per user as a string
Write a query that returns each user_id alongside a comma-separated, alphabetically sorted, deduplicated list of their merchants. Show both the PostgreSQL/BigQuery dialect and the MySQL dialect. Include an example of casting DECIMAL to text when building a merchant:spend string.
Part 6 — Python accumulation
Given a list of dictionaries (one per transaction row), write a Python function that returns a mapping of user_id → total amount using a single-pass loop. Amounts may arrive as floats or numeric strings. Handle missing or invalid values gracefully and avoid floating-point precision errors.
Hints
Hint 1
A window function adds a computed column without collapsing rows — think of OVER() as a movable lens that scans a subset of rows for each output row, while GROUP BY discards individual rows entirely.
Hint 2
For Part 3, construct a small table with two tied values followed by a lower value, then trace what number each function assigns to the row after the tie — that single example makes the RANK vs DENSE_RANK distinction concrete and memorable.
Hint 3
In Part 6, convert every amount to Decimal via str(raw_value) rather than Decimal(float_value) — passing a float directly to Decimal inherits its binary rounding error, whereas going through a string representation preserves the exact decimal digits.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Window Functions
A window function computes a result for every row by looking at a related set of rows — its "window" — without collapsing them into a single output row. GROUP BY reduces N rows to one row per group; a window function keeps all N rows and appends the computed value alongside each one.
Syntax skeleton:
function_name(expr) OVER (
PARTITION BY col -- optional: resets the window per group
ORDER BY col -- optional: defines row order within the window
ROWS BETWEEN ... -- optional: defines the frame
)
Practical use cases:
- Running total:
SUM(amount) OVER (PARTITION BY user_id ORDER BY transaction_ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)— cumulative spend per user over time. - Ranking within a group:
RANK()/DENSE_RANK()to find a user's top-N transactions by amount. - Row-over-row comparison:
LAG(transaction_ts)to compute time elapsed since a user's previous transaction (useful for velocity checks). - Moving average:
AVG(amount) OVER (ORDER BY transaction_ts ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). - Share of total:
amount / SUM(amount) OVER (PARTITION BY merchant)gives each transaction's fraction of that merchant's volume. - Deduplication: keep only the row where
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_ts DESC) = 1.
Example combining a running spend with the gap since the previous transaction:
SELECT
transaction_id,
user_id,
amount,
SUM(amount) OVER (
PARTITION BY user_id
ORDER BY transaction_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_spend,
transaction_ts
- LAG(transaction_ts) OVER (PARTITION BY user_id ORDER BY transaction_ts)
AS gap_since_prev
FROM transactions;
User 17 gets running totals of 45.80 then 166.79. The gap_since_prev column is NULL on each user's first row.
Part 2 — Join Types
| Join | What it returns |
|---|---|
INNER | Only rows that match on both sides |
LEFT | Every row from the left table; NULLs fill the right columns where no match exists |
RIGHT | Every row from the right table; NULLs fill the left columns — functionally equivalent to rewriting as a LEFT join with the tables swapped |
FULL OUTER | All rows from both sides; NULLs wherever either side has no match — useful for reconciliation between two data sources |
CROSS | Cartesian product (m × n rows, no join condition) — useful for generating all combinations, e.g. every merchant × every calendar date |
Key pitfalls:
- LEFT join silently becoming INNER: a
WHEREfilter on the right-side table eliminates the NULL rows, turning the outer join into an inner join. Move that condition into theONclause instead. - Fan-out inflating aggregates: if the join key is not unique on one side, matching rows duplicate, causing
SUMto overcount. Aggregate or deduplicate before joining.
Part 3 — RANK vs DENSE_RANK vs ROW_NUMBER
All three are window ranking functions, and all assign the same number to tied rows — except ROW_NUMBER, which breaks ties arbitrarily.
| amount | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 80 | 3 | 3 | 2 |
RANKskips positions after a tie (positions 1, 1, 3).DENSE_RANKnever skips (positions 1, 1, 2).ROW_NUMBERalways produces a unique sequence regardless of ties.
When to use each: DENSE_RANK for "the second-highest distinct value"; RANK for competition-style standings; ROW_NUMBER when you need exactly one row per group (e.g. deduplication or the most recent record).
Part 4 — GMV per Merchant
SELECT
merchant,
SUM(amount) AS gmv,
COUNT(*) AS txn_count
FROM transactions
WHERE currency = 'USD' -- filter before summing; never add across currencies
GROUP BY merchant
ORDER BY gmv DESC;
Expected output: Walmart 166.79, eBay 65.00, Target 23.15.
Keep amount as DECIMAL through the aggregation — casting to FLOAT for money introduces rounding error. If multiple currencies are present, join to an FX-rate table and convert to a single base currency before calling SUM.
Part 5 — Merchants per User as a String
PostgreSQL / BigQuery / SQL Server 2017+:
SELECT
user_id,
STRING_AGG(DISTINCT merchant, ', ' ORDER BY merchant) AS merchants
FROM transactions
GROUP BY user_id;
MySQL:
SELECT
user_id,
GROUP_CONCAT(DISTINCT merchant ORDER BY merchant SEPARATOR ', ') AS merchants
FROM transactions
GROUP BY user_id;
Dialect notes: SQL Server does not support DISTINCT inside STRING_AGG — deduplicate in a subquery first. MySQL's group_concat_max_len defaults to 1,024 bytes and silently truncates longer results.
Casting DECIMAL to text when building a merchant:spend string (PostgreSQL):
SELECT
user_id,
STRING_AGG(merchant || ':' || CAST(merchant_sum AS VARCHAR), ', ' ORDER BY merchant)
AS merchant_spend
FROM (
SELECT
user_id,
merchant,
SUM(CAST(amount AS DECIMAL(12, 2))) AS merchant_sum
FROM transactions
GROUP BY user_id, merchant
) t
GROUP BY user_id;
User 17 returns Walmart:166.79.
Part 6 — Python Dict Accumulation
from decimal import Decimal, InvalidOperation
from typing import Any, Dict, Iterable
def total_amount_by_user(rows: Iterable[Dict[str, Any]]) -> Dict[Any, Decimal]:
"""Return user_id -> total amount, using a single-pass loop.
Amounts may be floats or numeric strings. Invalid or missing values
are skipped. Decimal(str(x)) is used to avoid binary float rounding.
"""
totals: Dict[Any, Decimal] = {}
for row in rows:
user_id = row.get("user_id")
raw_amount = row.get("amount")
if user_id is None or raw_amount is None:
continue
try:
amount = Decimal(str(raw_amount)) # str() preserves exact decimal digits
except InvalidOperation:
continue
totals[user_id] = totals.get(user_id, Decimal("0")) + amount
return totals
if __name__ == "__main__":
rows = [
{"transaction_id": 1001, "user_id": 17, "merchant": "Walmart", "amount": 45.80},
{"transaction_id": 1002, "user_id": 22, "merchant": "Target", "amount": 23.15},
{"transaction_id": 1003, "user_id": 17, "merchant": "Walmart", "amount": "120.99"},
{"transaction_id": 1004, "user_id": 30, "merchant": "eBay", "amount": 65.00},
]
print(total_amount_by_user(rows))
# {17: Decimal('166.79'), 22: Decimal('23.15'), 30: Decimal('65.0')}
collections.defaultdict(Decimal) is an equally clean alternative. For large datasets the natural upgrade is df.groupby("user_id")["amount"].sum() in pandas, but showing the explicit loop demonstrates you understand what the aggregation is actually doing underneath.
Complexity: O(n) time, O(u) space where u is the number of distinct users.
Common mistake: passing the float directly to Decimal — Decimal(45.80) gives Decimal('45.7999999999999971578290569595992565155029296875'). Always go through str first.