SELECT p.name,p.expiry_period,vld.qty_available current_stock,COUNT(DISTINCT CASE WHEN t.type="sell_return" THEN t.id END) returns 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 p.enable_stock=1 AND p.expiry_period IS NOT NULL GROUP BY p.id,p.name,p.expiry_period,vld.qty_available ORDER BY expiry_period;