SELECT p.name,COUNT(DISTINCT t.id) purchase_orders,AVG(DATEDIFF(t.transaction_date,t.created_at)) lead_time FROM products p JOIN purchase_lines pl ON p.id=pl.product_id JOIN transactions t ON pl.transaction_id=t.id WHERE t.type="purchase" GROUP BY p.id,p.name ORDER BY lead_time;