Implement a custom ranking logic in SQL without using window functions.

Instruction: In PostgreSQL sales(product_id integer NOT NULL, quantity integer NOT NULL), rank each product appearing in sales by its total quantity without window functions. Use competition ranks with gaps after ties, such as 1, 1, 3. State the policy for products without sales.

Context: This question challenges candidates to devise alternative solutions to ranking, testing their creativity and deep understanding of SQL functionalities.

Updated

Official answer

Use competition ranking: equal totals receive the same rank and leave gaps. Assume PostgreSQL sales(product_id integer NOT NULL, quantity integer NOT NULL). Products without sales rows are excluded.

WITH totals AS (
  SELECT product_id, SUM(quantity) AS total_quantity
  FROM sales
  GROUP BY product_id
)
SELECT t.product_id, t.total_quantity,
       1 + (SELECT COUNT(*) FROM totals AS higher
            WHERE higher.total_quantity > t.total_quantity) AS sales_rank
FROM totals AS t
ORDER BY sales_rank, t.product_id;

Totals 100, 100 and 80 receive ranks 1, 1 and 3. COUNT(*) counts higher-ranked products, including tied products. COUNT(DISTINCT higher.total_quantity) would instead produce dense ranks 1, 1 and 2.

The product ID breaks display-order ties without changing rank. Define whether negative quantities represent returns and whether unsold products should join from a catalog with zero totals. The correlated comparison can be costly; a window RANK over aggregated totals is usually clearer when window functions are available. Validate rather than assume a particular execution plan.

Related Questions