Recursive select with conditions