Modified device selection sql that should be far more efficient. Test against a large dataset to see how much better. #249