Skip to content

SQL to find the most active META trader this month

Question

Each row of transactions_table records one trade between a buyer and a seller. Its integer columns are transaction_id, buyer_id and seller_id; it also stores the ticker in stock_symbol (text), the trade timestamp in transaction_date and the price in purchase_price (float).

Write a SQL query that returns the trader (or traders, if tied) with the largest number of META transactions over the last 30 days, counting both purchases and sales. Output trader_id and transactions, sorted by transactions descending.

Short answer

Unpivot buyers and sellers, count, then rank with ties. Filter to stock_symbol = 'META' and dates within 30 days of now, then UNION ALL the buyer_id and seller_id columns as a single trader_id. Group by trader to count transactions, apply RANK() (or DENSE_RANK()) ordered by count descending, and keep rank 1 so ties survive, ordering by the count.

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