SELECT p.name,COUNT(DISTINCT CASE WHEN t.type="stock_adjustment" THEN t.id END) adjustments,COUNT(DISTINCT pr.rack) storage_locations,vld.qty_available current_stock 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 LEFT JOIN product_racks pr ON p.id=pr.product_id WHERE p.enable_stock=1 GROUP BY p.id,p.name,vld.qty_available ORDER BY adjustments DESC;