For each category in sales, return weighted_avg_price = SUM(price * qty) / SUM(qty), rounded to 2 decimals.
Ignore rows where price or qty is NULL, or where qty is not positive. Only categories with a positive total quantity appear.
Input Table(s)
sales
| Column | Type | Meaning |
|---|
| id | INT | Sale line identifier |
| category | VARCHAR(50) | Product category |
| price | DECIMAL(10,2) | Unit price, non-negative or NULL |
| qty | INT | Units sold, may be NULL, zero or positive |
Key: id is the primary key.
Output Contract
| Column | Meaning |
|---|
| category | The category |
| weighted_avg_price | SUM(price * qty) / SUM(qty) over the category's valid rows, rounded to 2 decimal places |
One row per category that has at least one valid row. Sort by category ascending; each category appears once, so this order is unique.
Example
sales
| id | category | price | qty |
|---|
| 1 | food | 3.00 | 100 |
| 2 | food | 9.00 | 0 |
| 3 | food | NULL | 50 |
| 4 | food | 6.00 | NULL |
Expected output:
| category | weighted_avg_price |
|---|
| food | 3.00 |
Only row 1 is valid for food (row 2 has qty 0, row 3 has a NULL price, row 4 has a NULL qty). The weighted average is (3.00 * 100) / 100 = 3.00.
Constraints and Clarifications
-
The table has at most 10,000 rows.
-
price
is non-negative or NULL.
qty
may be NULL, zero or positive.
-
A row counts only when both
price
and
qty
are present and
qty
is greater than 0. Apply the same rule to the numerator and the denominator.
-
A category with no valid rows does not appear in the output.
-
A NULL
category
, if present, is grouped like any other value and sorts last.