# Accounts Spanning Three or More Stages

**Type:** SOQL · **Difficulty:** Hard · **Topics:** COUNT_DISTINCT, HAVING, GROUP BY

Practice this problem interactively (write and run your SOQL against realistic data): https://www.forcechallenges.com/problems/accounts-spanning-multiple-stages

## Problem

**Scenario**
Account executives want to find customers whose sales pipeline is spread across the sales process, not stuck in one stage. An Account that has Opportunities in several different stages is considered to have a broad, mature pipeline.

**Task**
Write one SOQL query on `Opportunity` that:
1. Ignores Opportunities that are not linked to an Account (`AccountId` is null).
2. Groups the remaining Opportunities by `AccountId`.
3. Keeps only Accounts whose Opportunities cover **at least 3 distinct values of `StageName`**.
4. Sorts the Accounts by their combined Opportunity `Amount`, **highest first**.

**Expected output**
One row per qualifying Account with three columns: `AccountId`, `stages` (the number of distinct stages) and `total` (the sum of `Amount`).

**Example**
Account A has Opportunities in Prospecting (100), Proposal (200) and Closed Won (300). Account B has two Opportunities, both Prospecting (500 and 400). Account C has Prospecting (50) and Proposal (60).
- A has 3 distinct stages and total 600, so it is returned.
- B has 1 distinct stage even though its total is 900, so it is excluded.
- C has only 2 distinct stages, so it is excluded.

Result: A with stages = 3 and total = 600.

## Constraints

Use a single query on Opportunity with GROUP BY AccountId. Count distinct stages with COUNT_DISTINCT(StageName) in HAVING. Exclude Opportunities that have no Account. Alias the columns exactly as `stages` and `total`.

---
Source: ForceChallenges · last updated 2026-10-23
