SELECT p.name,AVG(DATEDIFF(t_sale.transaction_date,t_purchase.transaction_date)) lead_time,COUNT(t_sale.id) sales,SUM((tsl.unit_price_inc_tax-pl.purchase_price)*tsl.quantity) profit FROM products p JOIN purchase_lines pl ON p.id=pl.product_id JOIN transactions t_purchase ON pl.transaction_id=t_purchase.id JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t_sale ON tsl.transaction_id=t_sale.id WHERE t_purchase.type="purchase" AND t_sale.type="sell" GROUP BY p.id,p.name ORDER BY lead_time;