Skip to content

SQL for the pair of traders with nearest median P&L

Question

Two tables are available:

  • traders(id INTEGER, name VARCHAR)
  • trades(id INTEGER, trader_id INTEGER, profit FLOAT)

Considering only traders who have made at least one trade, write a SQL query that finds the two traders whose median profit per trade are closest to each other. Return their names and the absolute gap between the medians, as columns trader1_name, trader2_name, median_profit_diff.

Short answer

Median per trader, self-join on pairs, keep the smallest gap. In a CTE, inner-join traders to trades and compute PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY profit) grouped by trader (the inner join drops traders with no trades). Join the CTE to itself with a.id < b.id so each pair appears once, compute ABS(a.median - b.median), order ascending and LIMIT 1. The pairing step is O(n2)O(n^2) in the number of traders.

Adapted from OpenQuant; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question

Start with a free lesson: Probability Fundamentals is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.

Read it free