I think if you extracted each query here into a function with a name that clearly says what it does this whole section of code would be a lot more readable. As it is, I can puzzle through it but I can't retain it and I know it will be difficult any time someone comes back to it.