Easy Solution | MySQL | 2 Approaches 😉
1. Easy Solution by LEFT JOIN & Between\n- Time complexity: 647ms (Beats 77.21%)\n\n- Space complexity: O(N)\n\n# Code\nmysql []\nSELECT \n    p.product_id,\n  
# 1. Easy Solution by LEFT JOIN & Between\n- Time complexity: 647ms (Beats 77.21%)\n\n- Space complexity: O(N)\n\n# Code\n```mysql []\nSELECT \n    p.product_id,\n    IFNULL(ROUND(SUM(u.units * p.price) / SUM(u.units), 2), 0) AS average_price\nFROM prices p LEFT JOIN unitssold u \n    ON p.product_id = u.product_id \n    AND u.purchase_date BETWEEN p.start_date AND p.end_date\nGROUP BY p.product_id;\n```\n\n# 2. Optimal Solution by LEFT JOIN & Window function\n- Time complexity: 685ms (Beats 62.63%)\n\n- Space complexity: O(N+M) => N for Price tables row numbers & M for Unitssold tables row numbers\n\n# Code\n```mysql []\nSELECT \n    DISTINCT(p.product_id),\n    IFNULL(ROUND(SUM(p.price * u.units) OVER w / SUM(u.units) OVER w, 2), 0) AS average_price\nFROM  prices p \nLEFT JOIN unitssold u \n    ON p.product_id = u.product_id \n    AND u.purchase_date BETWEEN p.start_date AND p.end_date\nWINDOW w AS (PARTITION BY p.product_id);\n```
['MySQL']