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

Last Person To Fit In The Bus

/challenges/last-person-to-fit-in-the-bus

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/Last Person to Fit in the Bus
Challenge DetailMediumReviewed 2026-04-20

Last Person to Fit in the Bus

Find the person_name of the last person that can fit on the bus without exceeding the weight limit of 1000.

Window FunctionsAggregation

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

2026-01-12Medium

Last Person to Fit in the Bus

Find the person_name of the last person that can fit on the bus without exceeding the weight limit of 1000.

Available Tables:
SQL Editor
Loading...

What This Challenge Is Testing

Running totals are one of the most useful window-function patterns in analytics and operations. The exact shape appears in capacity planning, inventory thresholds, credit exposure checks, and any sequence where you need to know the last safe row before crossing a limit.

Topic Tags

AnalyticsWindow Functions

Schema At A Glance

queue
person_idperson_nameweightturn

Solution Approaches

01

Window SUM for cumulative weight

WITH queue_weights AS (
  SELECT
    person_name,
    turn,
    SUM(weight) OVER (ORDER BY turn) AS cum_weight
  FROM queue
)
SELECT
  person_name
FROM queue_weights
WHERE cum_weight <= 1000
ORDER BY cum_weight DESC
LIMIT 1

This is the standard solution. The window SUM builds the running weight by boarding order, and the final filter keeps only the feasible passengers before selecting the latest one.

02

Self-correlated cumulative sum

SELECT
  q1.person_name
FROM queue q1
WHERE (
  SELECT SUM(q2.weight)
  FROM queue q2
  WHERE q2.turn <= q1.turn
) <= 1000
ORDER BY q1.turn DESC
LIMIT 1

This version avoids window functions and can help explain the logic from first principles. It is less efficient on larger tables, but it makes the cumulative condition very explicit.

Common Pitfalls

The main mistake is ordering by weight instead of by turn. The constraint is about boarding sequence, so the running total must follow turn order exactly. Another bug is choosing the maximum single weight under 1000 instead of the last cumulative total under 1000.

Frequently Asked Questions

Why is ORDER BY turn essential here?

Because the bus fills in queue order, not by passenger weight. The cumulative sum must follow the boarding sequence or the answer no longer reflects the real process.

What concept is this challenge teaching?

It teaches running totals with window functions: keeping row-level detail while also carrying forward an ordered cumulative metric.

Concept Guides

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

Calculating Running Totals & Moving Averages in SQL

How do you calculate "Year to Date" revenue or a "7-Day Moving Average" in SQL? The answer is Window Functions. Learn how to look back across rows without using self-joins.

Understanding SQL Window Functions: A Visual Guide

Master ROW_NUMBER, RANK, and running totals with interactive visualizations. See exactly how window functions process your data row by row.

SQL Window Frames: ROWS vs RANGE

Learn how ROWS and RANGE window frames change results, avoid hidden pitfalls, and build correct moving calculations with clear, runnable examples.

Topic Hubs

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

Advanced SQL

Advanced query patterns

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

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.

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

Rank ScoresMedium

Assign tied scores the same rank while keeping the next rank consecutive with no gaps.

Exchange SeatsMedium

Swap every pair of adjacent seat IDs while leaving the final row untouched if the seat count is odd.

Product Price at a Given DateMedium

Reconstruct each product’s price as of a snapshot date, including products that had not changed yet and still use the default price.

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed