Capital Gain/Loss

4pts
Robinhood

Problem Statement

A stock brokerage platform needs to calculate the net profit or loss for its users. You are given a table containing all buy and sell operations.

Write an SQL query to report the Capital gain/loss for each stock.

Rules:

  • The capital gain/loss of a stock is the total sum after completing all sell and buy operations for that stock.
  • Every Buy operation for a stock has a corresponding Sell operation eventually.
  • The result column should be named capital_gain_loss.
  • Results must be sorted by capital_gain_loss in descending order.
Tests your understanding of
Basic SQL, Aggregation, CASE WHEN and GROUP BY

Input Tables

stocks
stock_name(VARCHAR)operation(VARCHAR)operation_day(INTEGER)price(INTEGER)
LeetcodeBuy11000
Corona MasksBuy210
LeetcodeSell59000
HandbagsBuy1730000
Corona MasksSell31010
Corona MasksBuy41000
Corona MasksSell5500
Corona MasksBuy61000
Corona MasksSell1010000
HandbagsSell297000
LeetcodeBuy11100
LeetcodeSell15100

Expected Output

stock_name(VARCHAR)capital_gain_loss(INTEGER)
Corona Masks9500
Leetcode8000
Handbags-23000

Tags

MediumBasic SQLAggregationCASE WHENGROUP BY
10-15 min
92%

Hints