SELECT p.name,AVG(ABS(actual.quantity-forecast.quantity)/NULLIF(forecast.quantity,0))*100 forecast_error FROM products p JOIN (SELECT product_id,DATE(transaction_date) date,SUM(quantity) quantity FROM transaction_sell_lines tsl JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY product_id,DATE(transaction_date)) actual ON p.id=actual.product_id JOIN (SELECT product_id,DATE(transaction_date) date,AVG(quantity) quantity FROM transaction_sell_lines tsl JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY product_id,DATE(transaction_date)) forecast ON p.id=forecast.product_id GROUP BY p.id,p.name ORDER BY forecast_error;