Optimized histogram query generator