Fixing syntax of one of the worse queries I have ever seen