Skip to content

Commit d419331

Browse files
committed
Section 02 : Basic Agg : part 01 - solved error in p2
1 parent 7c4a12c commit d419331

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed
Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
1-
SELECT u.product_id, ROUND(SUM(p.price * u.units) / SUM(u.units), 2) AS average_price
2-
FROM Prices p
3-
JOIN UnitsSold u ON p.product_id = u.product_id AND u.purchase_date BETWEEN p.start_date AND p.end_date
4-
GROUP BY u.product_id;
1+
SELECT
2+
p.product_id,
3+
COALESCE(ROUND(SUM(p.price * COALESCE(u.units, 0)) / GREATEST(SUM(u.units), 1), 2), 0) AS average_price
4+
FROM
5+
Prices p
6+
LEFT JOIN
7+
UnitsSold u
8+
ON
9+
p.product_id = u.product_id
10+
AND u.purchase_date BETWEEN p.start_date AND p.end_date
11+
GROUP BY
12+
p.product_id;
13+
14+
-- Solved the error by modifying the SQL query to include products from the Prices table that have no corresponding entries in the UnitsSold table. This was achieved by using a LEFT JOIN and COALESCE to handle the cases where there are no matching units sold for a product.

0 commit comments

Comments
 (0)