Orders With Maximum Quantity Above Average - Problem

You have a table OrdersDetails that contains information about products ordered in different orders. Each row represents one product in an order with its quantity.

Your task is to find imbalanced orders. An imbalanced order is one where:

  • The maximum quantity of any single product in the order is strictly greater than the average quantity of that order

For each order:

  • Average quantity = (total quantity of all products) ÷ (number of different products)
  • Maximum quantity = highest quantity of any single product

Return the order_id of all imbalanced orders in any order.

Table Schema

OrdersDetails
Column Name Type Description
order_id PK int Identifier for the order
product_id PK int Identifier for the product
quantity int Quantity of the product ordered
Primary Key: (order_id, product_id)
Note: Each order can have multiple products, and each (order_id, product_id) combination is unique

Input & Output

Example 1 — Mixed Imbalanced Orders
Input Table:
order_id product_id quantity
1 101 30
1 102 10
2 201 20
2 202 20
3 301 50
3 302 30
3 303 20
Output:
order_id
1
3
💡 Note:

Order 1: MAX(30) > AVG((30+10)/2 = 20) ✓ Imbalanced

Order 2: MAX(20) = AVG((20+20)/2 = 20) ✗ Balanced

Order 3: MAX(50) > AVG((50+30+20)/3 = 33.33) ✓ Imbalanced

Example 2 — Single Product Orders
Input Table:
order_id product_id quantity
100 1001 25
200 2001 15
Output:
order_id
💡 Note:

Orders with single products have MAX = AVG, so none are imbalanced. Order 100: MAX(25) = AVG(25). Order 200: MAX(15) = AVG(15).

Constraints

  • 1 ≤ order_id ≤ 10^6
  • 1 ≤ product_id ≤ 10^6
  • 1 ≤ quantity ≤ 10^5
  • Each (order_id, product_id) combination is unique

Visualization

Tap to expand
Orders With Maximum Quantity Above Average INPUT order_id product quantity 1 A 10 1 B 5 1 C 3 2 A 8 2 B 8 3 A 12 3 B 2 Orders grouped by ID: Order 1 [10,5,3] Order 2 [8,8] Order 3 [12,2] ALGORITHM STEPS 1 Group by Order ID Collect quantities per order 2 Calculate Average avg = sum / count products 3 Find Maximum Qty max_qty for each order 4 Compare max vs avg Select if max > avg Order Max Avg Result 1 10 6.0 OK 2 8 8.0 NO 3 12 7.0 OK 10 > 6.0 OK | 8 = 8.0 NO | 12 > 7.0 OK FINAL RESULT Qualifying Orders: Order 1 max=10 > avg=6.0 Order 3 max=12 > avg=7.0 Rejected: Order 2 max=8 NOT > avg=8 OUTPUT: order_id: [1, 3] Key Insight: The condition requires STRICTLY GREATER (>), not greater-than-or-equal. Order 2 fails because max(8,8)=8 equals avg(16/2)=8, not strictly greater. Use GROUP BY with HAVING MAX(qty) > SUM(qty)/COUNT(DISTINCT product) in SQL. TutorialsPoint - Orders With Maximum Quantity Above Average | Optimal Solution
Asked in
Amazon 28 Microsoft 15 Google 12
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen