SELECT p.name,COUNT(DISTINCT t_po.id) purchase_orders,COUNT(DISTINCT t_so.id) sales_orders,AVG(DATEDIFF(t_so.transaction_date,t_po.transaction_date)) avg_dock_time FROM products p JOIN purchase_lines pl ON p.id=pl.product_id JOIN transactions t_po ON pl.transaction_id=t_po.id JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t_so ON tsl.transaction_id=t_so.id WHERE t_po.type="purchase" AND t_so.type="sell" GROUP BY p.id,p.name ORDER BY avg_dock_time;