SELECT p.name,COUNT(DISTINCT CASE WHEN vld.qty_available=0 THEN DATE(t.transaction_date) END) stockout_days,COUNT(DISTINCT DATE(t.transaction_date)) total_days FROM products p LEFT JOIN variation_location_details vld ON p.id=vld.product_id LEFT JOIN transaction_sell_lines tsl ON p.id=tsl.product_id LEFT JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY p.id,p.name ORDER BY stockout_days/total_days;