KatInterview

SQL Window Functions, Join Types, and Python Aggregation

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsjoinsaggregation

Last 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_iduser_idmerchantamountcurrencytransaction_ts
100117Walmart45.80USD2023-07-12 14:02:08
100222Target23.15USD2023-07-12 15:10:44
100317Walmart120.99USD2023-07-13 09:21:11
100430eBay65.00USD2023-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.