Final SQL optimized solution.