Calculate Compressed Mean
EasyUpdated: Jul 1, 2025
Practice on:
Problem
Table: Orders
+-------------------+------+
| Column Name | Type |
+-------------------+------+
| order_id | int |
| item_count | int |
| order_occurrences | int |
+-------------------+------+ order_id is column of unique values for this table.
This table contains order_id, item_count, and order_occurrences.
Write a solution to calculate the average number of items per order, rounded to 2 decimal places.
Return the result table inany order .
The result format is in the following example.
Examples
Example 1:
Input:
Orders table:
+----------+------------+-------------------+
| order_id | item_count | order_occurrences |
+----------+------------+-------------------+
| 10 | 1 | 500 |
| 11 | 2 | 1000 |
| 12 | 3 | 800 |
| 13 | 4 | 1000 |
+----------+------------+-------------------+
**Output**
+-------------------------+
| average_items_per_order |
+-------------------------+
| 2.70 |
+-------------------------+
**Explanation**
The calculation is as follows:
- Total items: (1 * 500) + (2 * 1000) + (3 * 800) + (4 * 1000) = 8900
- Total orders: 500 + 1000 + 800 + 1000 = 3300
- Therefore, the average items per order is 8900 / 3300 = 2.70
Solution
Method 1 – Weighted Average Using SUM and ROUND
Intuition
To find the average number of items per order, we need the total number of items (item_count × order_occurrences for each row) divided by the total number of orders (sum of order_occurrences). This is a weighted mean, and SQL's SUM and ROUND functions make it straightforward.
Approach
- Use SUM to calculate the total items: sum of (item_count × order_occurrences).
- Use SUM to calculate the total orders: sum of order_occurrences.
- Divide total items by total orders to get the mean.
- Use ROUND to round the result to 2 decimal places.
- Return the result as average_items_per_order.
Code
MySQL
SELECT ROUND(SUM(item_count * order_occurrences) / SUM(order_occurrences), 2) AS average_items_per_order
FROM Orders;
Complexity
- ⏰ Time complexity: O(n) — n is the number of rows in Orders (single scan for SUM).
- 🧺 Space complexity: O(1) — Only accumulators are used.