Select the Best Quality Snapshot per Team
Assign deterministic ROW_NUMBER values in a CTE and filter to row_num = 1.
- CTEs
- Window functions
- Subqueries
- Filtering
- Sorting
Exercise brief
Understand the request
Quality program manager A scorecard needs exactly one representative snapshot per team, preferring the latest period when quality is tied.
A scorecard needs exactly one representative snapshot per team, preferring the latest period when quality is tied. Assign deterministic ROW_NUMBER values in a CTE and filter to row_num = 1.
Return
- Return team_name, snapshot_id, period_no, and quality_score.
- Order by team_name.
Constraints
- Partition by team_name.
- Order by quality_score DESC, period_no DESC, snapshot_id DESC.
- Filter the window result in the outer query.
Data you will use
Review the relevant tables before deciding how to join, filter, or aggregate them.
team_metrics
snapshot_idINTEGERteam_nameVARCHAR(40)period_noINTEGERrevenueINTEGERtickets_closedINTEGERquality_scoreINTEGER
Hints, when you need them
Open one clue at a time so you still do the reasoning.
Hint 1
This is an exact-one-per-group contract, so use ROW_NUMBER rather than RANK.
Hint 2
All tie-breakers belong inside the window ORDER BY.
Hint 3
Window aliases are filtered in an outer query or CTE consumer.
Verified SQL answer
Attempt the problem first, then compare structure and reasoning—not just syntax.
Reveal solution and explanation
WITH ranked_quality AS (SELECT team_name, snapshot_id, period_no, quality_score, ROW_NUMBER() OVER (PARTITION BY team_name ORDER BY quality_score DESC, period_no DESC, snapshot_id DESC) AS row_num FROM team_metrics) SELECT team_name, snapshot_id, period_no, quality_score FROM ranked_quality WHERE row_num = 1 ORDER BY team_name;Why this works
A total window order makes ROW_NUMBER deterministic; the outer filter is required because window values are calculated after WHERE.
Success check
Exactly one stable winner is selected per team despite tied quality scores.
Expected result
Use this output to verify values, aliases, ordering, and row count.
| team_name | snapshot_id | period_no | quality_score |
|---|---|---|---|
| alpha | 105 | 6 | 97 |
| beta | 205 | 6 | 96 |
| gamma | 303 | 4 | 96 |
Learn the concepts behind this answer
Strengthen your understanding with these targeted learning topics:
Continue practicing
Build the next SQL skill
Ranking & NTH Value
Solve deterministic ranking, top-N, distribution, positional-frame, and rolling-window problems.
SQL Subqueries
Practice scalar, derived-table, correlated, EXISTS, NULL-safe anti-subquery, quantified, and row-subquery patterns.
Self Joins & Hierarchical Queries
Query organization charts, trees, and parent-child relationships.
Open the interactive workspace and practice across SQL topics.