You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN a.Start_date = b.max_sd AND a.Start_date <> b.min_sd THEN ' at line 4