SELECT c.name category,AVG(DATEDIFF(t_sale.transaction_date,t_purchase.transaction_date)) inventory_days,AVG(t_sale.final_total-pl.purchase_price*pl.quantity) gross_profit FROM categories c JOIN products p ON c.id=p.category_id 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 c.id,c.name ORDER BY inventory_days;