Skip to content

LeetCode 1082: Sales Analysis I

A clear explanation of finding the best seller(s) by total price using GROUP BY, SUM, and a subquery for the maximum.

Problem Restatement

We have a Sales(seller_id, product_id, buyer_id, sale_date, quantity, price) table.

Report the seller(s) with the highest total sale price.

Edge Cases

  • Match the aggregate to the question: use raw COUNT or SUM for rows/amounts, and COUNT(DISTINCT ...) only for unique entities.
  • Tie cases should return every qualifying row unless the statement asks for a single row.
  • For outer joins, keep filters on the joined table in the ON clause when unmatched rows must remain visible.

Common Pitfalls

  • Do not put aggregate filters in WHERE; use HAVING after GROUP BY.
  • When the answer needs all tied winners, avoid LIMIT 1 unless the statement explicitly asks for one row.

Implementation

SELECT seller_id
FROM Sales
GROUP BY seller_id
HAVING SUM(price) = (
    SELECT MAX(total)
    FROM (
        SELECT SUM(price) AS total
        FROM Sales
        GROUP BY seller_id
    ) AS sub
);

Code Explanation

The inner query computes total sales per seller.

MAX(total) finds the highest total.

The outer HAVING clause keeps only sellers with that maximum total, handling ties.