SELECT p.product_id,
ROUND(COALESCE(SUM(price * units) / NULLIF(SUM(units), 0), 0), 2) AS average_price
FROM Prices p
JOIN UnitsSold u ON u.product_id = p.product_id
AND u.purchase_date BETWEEN p.start_date AND p.end_date
GROUP BY p.product_id;
Only passes 15/17 test cases, not sure why
-
Tried using NULLIF, COALESCE function
-
syntax correct, passes test case in leetcode
2
Answers
You should still output a product even if it has no entry in the
UnitsSold
table, so use a left outer join instead of an inner join.As you can see
For the price you can use 0 as alternative Value for NULL
but for divider you nned to return 1
Final word before this will be deleted, you need only the last query for your test
fiddle