Matt, 1st thing I see is you have "WHERE" twice in one WHERE CLAUSE....
"where on_contract <="
should be
"and on_contract <="
As far a formatting the post, I use the "#" tool on the "post edit toolbar". This is {CODE} insert block. It also seems to be much better if I put an added [space] at the end of each line??.
Once you understand the BITs, all the pieces come together