SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed

New conversation

What can I help with?

Ask about this page, get a hint on a challenge, or explore SQL concepts.

I know what's on this page and can give answers grounded in SQL Boy content.

Current page

Capital Gain Loss

/challenges/capital-gain-loss

Usage status will load after login
SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog
SQL Challenges/Capital Gain/Loss
Challenge DetailMediumReviewed 2026-04-20

Capital Gain/Loss

Report the Capital gain/loss for each stock. The Capital gain/loss of a stock is total gain or loss after buying and selling the stock one or many times.

AggregationCase When

This challenge now meets the current minimum standard for sitemap inclusion and independent indexing.

2026-01-15Medium

Capital Gain/Loss

Report the Capital gain/loss for each stock. The Capital gain/loss of a stock is total gain or loss after buying and selling the stock one or many times.

Available Tables:
SQL Editor
Loading...

What This Challenge Is Testing

This is a sign-normalization problem. Financial reporting, inventory movement, and ledger analysis often depend on converting different event types into positive and negative contributions so a single aggregate can compute the final net result.

Topic Tags

AnalyticsCase WhenAggregations

Schema At A Glance

stocks
stock_nameoperationoperation_dayprice

Solution Approaches

01

CASE inside SUM to normalize cash direction

SELECT
  stock_name,
  SUM(
    CASE
      WHEN operation = 'Buy' THEN -price
      ELSE price
    END
  ) AS capital_gain_loss
FROM stocks
GROUP BY stock_name

This is the cleanest solution. It translates each row into signed cash flow first, then adds the flows per stock to get the net gain or loss.

02

Separate buys and sells, then net them out

WITH stock_flows AS (
  SELECT
    stock_name,
    SUM(CASE WHEN operation = 'Sell' THEN price ELSE 0 END) AS total_sold,
    SUM(CASE WHEN operation = 'Buy' THEN price ELSE 0 END) AS total_bought
  FROM stocks
  GROUP BY stock_name
)
SELECT
  stock_name,
  total_sold - total_bought AS capital_gain_loss
FROM stock_flows

The two-bucket version is more verbose, but it can be easier to explain when you want to show the inflow and outflow components separately before subtracting them.

Common Pitfalls

The main mistake is summing raw prices without flipping the sign for buys. That treats money spent as if it were profit. Another is trying to match buy and sell rows pairwise when the prompt only asks for total net result per stock.

Frequently Asked Questions

Why can we ignore exact buy-sell pairing here?

Because the metric asked for in this challenge is total capital gain or loss per stock after all transactions, not realized gain per individual lot. Net cash flow is enough for this schema and prompt.

What concept does this challenge reinforce?

It reinforces conditional aggregation and sign normalization: translating different row types into a common metric scale so they can be added meaningfully.

Concept Guides

Use these guides when you want the fuller explanation behind the SQL pattern this challenge is testing.

SQL Conditional Aggregation: Beyond Basic GROUP BY

Turn multiple queries into one with conditional aggregation. Learn how CASE WHEN inside aggregate functions creates powerful single-query reports and pivot tables.

SQL CASE Statements: Adding Logic to Your Queries

Learn how to add conditional logic to your SQL queries using CASE statements. Transform data and categorize results with ease.

SQL Aggregate Functions: COUNT, SUM, AVG, MIN, MAX Explained

Master SQL aggregate functions with practical examples. Learn when and how to use COUNT, SUM, AVG, MIN, and MAX effectively.

Topic Hubs

If this problem exposed a deeper weakness, use a topic hub to move through a curated cluster instead of random article hopping.

Analytics

Analytics SQL and business metrics

A practical cluster for cohorts, funnels, customer value, and the kinds of reporting questions teams actually ask every week.

Advanced SQL

Advanced query patterns

Use this path when you are moving beyond beginner SELECT queries into CTEs, window functions, and conditional logic.

Practice Path

If you want the rotating practice flow, open this same question from the daily stream. If you want interview-style packaging, continue into the interview pool after this rep.

Back to ChallengesOpen In DailyBrowse Interviews

Related Challenges

Monthly Transactions IMedium

Roll monthly transaction reporting into one query while splitting total volume from approved volume by country.

Friend Requests I: Overall Acceptance RateMedium

Calculate overall friend request acceptance rate while separating request volume from accepted pairs cleanly.

Customers Who Bought All ProductsMedium

Return only the customers whose distinct purchased product set covers every product listed in the catalog.

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed