Capital Gain/Loss per User

4pts
Fintech

Problem Statement

You are analyzing a fintech database for stock market activity. Each record is either a Buy or a Sell transaction.

Write an SQL query to report the Capital Gain/Loss for each user.

Rules:

  • Capital Gain/Loss is calculated as the sum of (Sell Price - Buy Price) for all trades.
  • Every Buy transaction will eventually have a corresponding Sell transaction (or vice versa depending on the period).
  • Output columns: user_id, capital_gain_loss.
  • Results must be sorted by user_id in ascending order.
Tests your understanding of
Conditional Aggregation, Financial Logic and Arithmetic

Input Tables

Stocks
user_id(INTEGER)operation(VARCHAR)operation_day(INTEGER)price(INTEGER)
1Buy11000
1Sell51500
2Buy17000
2Sell101000
1Buy123000
1Sell153500
Users
user_id(INTEGER)username(VARCHAR)
1Trader_Alpha
2Trader_Beta
Audit_Trail
transaction_id(INTEGER)user_id(INTEGER)verified(BOOLEAN)
991true

Expected Output

user_id(INTEGER)capital_gain_loss(INTEGER)
11000
2-6000

Tags

MediumConditional AggregationFinancial LogicArithmetic
15-20 min
78%

Hints