Multi-Table Sales Analytics with Referral Tracking
SQL & DataAuto-graded · 13 test casesLast updated
Tests relational data manipulation through joins, aggregations, filtering, and ranking across interconnected tables.
You're building an analytics dashboard for an online bookstore. Given four related tables as lists of rows, compute three separate metrics.
Tables
books: Each row is [book_id, title, author_id, price]
book_id: unique identifiertitle: book title stringauthor_id: foreign key to authors tableprice: list price as a float
authors: Each row is [author_id, name, personal_url]
author_id: unique identifiername: author name stringpersonal_url: author's website URL string (may beNone)
transactions: Each row is [transaction_id, book_id, customer_id, quantity, pay_method, amount]
transaction_id: unique identifierbook_id: foreign key to books tablecustomer_id: foreign key to customers tablequantity: number of copies purchasedpay_method: payment method string (e.g., "Visa", "PayPal")amount: actual charged amount as a float
customers: Each row is [customer_id, name, referred_by_customer_id]
customer_id: unique identifiername: customer name stringreferred_by_customer_id: ID of the customer who referred this customer (Noneif not referred)
Task
Return a dictionary with four keys:
-
top_payment_methods: List of up to 5 payment methods with highest total sales. Each entry is a dict withpay_method(string) andtotal_sales(float). Sort by total sales descending, then by method name ascending for ties. -
proportion_authors_zero_sales: Float representing the proportion of authors who have never sold any books. An author with no books in the books table counts as having zero sales. -
proportion_authors_url_contains_keyword: Float representing the proportion of authors whosepersonal_urlcontains the givenkeywordsubstring (case-sensitive). ANoneURL does not contain any keyword. -
top_referrers: List of up to 5 customers who referred others, ranked by the average list price of books their referees purchased. Each entry is a dict withcustomer_id(int) andaverage_price(float). Only include purchases by customers who were referred by someone. If a referee makes multiple purchases, count each transaction separately when computing the average. Sort by average price descending, then by customer_id ascending for ties.
Constraints
- All tables may be empty
- 0 ≤ number of books, authors, transactions, customers ≤ 10,000
book_id,author_id,customer_id,transaction_idare unique within their tables- Foreign key references may point to non-existent records (treat as missing data)
priceandamountare non-negative floatsquantityis a positive integer- The
keywordparameter is a non-empty string - When computing proportions with zero authors, return 0.0
Examples
Example 1
Input: compute_sales_metrics([[1, 'SQL 101', 10, 29.99], [2, 'Python', 11, 39.99], [3, 'ML Guide', 10, 49.99]], [[10, 'Alice', 'example.com/alice'], [11, 'Bob', 'example.com/bob_keyword'], [12, 'Carol', 'example.com/carol']], [[1001, 1, 501, 2, 'Visa', 59.98], [1002, 2, 502, 1, 'PayPal', 39.99], [1003, 3, 503, 1, 'Visa', 49.99]], [[501, 'Dan', None], [502, 'Eve', 501], [503, 'Frank', 502]], 'keyword')
Output: {'top_payment_methods': [{'pay_method': 'Visa', 'total_sales': 109.97}, {'pay_method': 'PayPal', 'total_sales': 39.99}], 'proportion_authors_zero_sales': 0.3333333333333333, 'proportion_authors_url_contains_keyword': 0.3333333333333333, 'top_referrers': [{'customer_id': 502, 'average_price': 49.99}, {'customer_id': 501, 'average_price': 39.99}]}
Hints
Hint 1
For top payment methods, aggregate by the recorded transaction amount, not price multiplied by quantity.
Hint 2
Authors with zero sales include those who have no books and those whose books never appear in transactions.
Hint 3
When computing referrer averages, use the book's list price and count each transaction separately, regardless of quantity purchased.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires three separate aggregations over interconnected relational data. The strategy is to build lookup maps that simulate database joins, then process transactions once to extract all needed information.
Payment Methods: Group transactions by payment method and sum the amount field. Sort by total descending, breaking ties with method name ascending, and take the top 5.
Author Proportions:
- For zero-sales authors, check which authors have no books that appear in the set of transacted book IDs. Authors without any books also count as zero-sales.
- For keyword matches, perform substring search on each author's URL, treating
Noneas an empty string that contains no keyword. - Divide each count by the total number of authors.
Top Referrers: For each transaction, look up the buyer's referrer. If the buyer was referred and the book exists in the books table, record the book's list price against that referrer. Compute the average price per referrer (counting each transaction separately), sort by average descending with customer ID as tiebreaker, and take the top 5.
Why It Works
The core challenge is correctly handling missing data and join semantics:
-
Zero-sales detection requires checking both books and transactions. A left-join approach would keep all authors, then flag those whose books never sold. The Python equivalent iterates through authors and checks whether any of their books appears in the sold set.
-
Referrer averages must exclude transactions where the customer has no referrer or the book is unknown. This mimics an inner join. Each transaction contributes the book's list price once, regardless of quantity.
-
Tie-breaking ensures deterministic results by using a secondary sort key (method name or customer ID) in ascending order.
Complexity
-
Time: O(B + A + T + C + M log M + R log R), where B is books, A is authors, T is transactions, C is customers, M is distinct payment methods, and R is distinct referrers. The zero-sales check as written is O(A × B) but can be optimized to O(A + B) by pre-building a set of author IDs with sales.
-
Space: O(B + C + T) for the lookup maps, the transacted book set, and the per-referrer price lists.
Full Solution
from typing import Dict, List
def compute_sales_metrics(books: List[List], authors: List[List], transactions: List[List], customers: List[List], keyword: str) -> Dict:
book_prices = {book[0]: book[3] for book in books}
payment_totals = {}
transacted_book_ids = set()
customer_to_referrer = {cust[0]: cust[2] for cust in customers}
referrer_to_prices = {}
for txn in transactions:
book_id = txn[1]
customer_id = txn[2]
payment_method = txn[4]
charged_amount = txn[5]
payment_totals[payment_method] = payment_totals.get(payment_method, 0) + charged_amount
transacted_book_ids.add(book_id)
referring_customer = customer_to_referrer.get(customer_id)
if referring_customer is not None and book_id in book_prices:
referrer_to_prices.setdefault(referring_customer, []).append(book_prices[book_id])
sorted_methods = sorted(payment_totals.items(), key=lambda x: (-x[1], x[0]))[:5]
authors_with_no_sales = sum(
1 for author in authors
if not any(b[2] == author[0] and b[0] in transacted_book_ids for b in books)
)
authors_with_keyword = sum(1 for author in authors if keyword in (author[2] or ""))
total_authors = len(authors)
referrer_list = []
for ref_id, prices in referrer_to_prices.items():
referrer_list.append({
"customer_id": ref_id,
"average_price": sum(prices) / len(prices)
})
referrer_list.sort(key=lambda x: (-x["average_price"], x["customer_id"]))
return {
"top_payment_methods": [{"pay_method": m, "total_sales": t} for m, t in sorted_methods],
"proportion_authors_zero_sales": authors_with_no_sales / total_authors if total_authors else 0.0,
"proportion_authors_url_contains_keyword": authors_with_keyword / total_authors if total_authors else 0.0,
"top_referrers": referrer_list[:5],
}