What criteria are used to pick crews for missions? Do astronauts just wait their turn or do they get picked on merit?

I am not sure exactly what the process is to pick crews. There are times in which it is not clear. You look at a given crew sometimes, and you wonder. Although, when the result is finally in, it is very clear there was logic in that process. And other times, you do see that a given scientific discipline or a given talent is brought to bear in a mission. So I do think there is a lot of logic in it, even though, I do not know how that process works.