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