Add missing trim() around Sqlserver queries.

This solves issues with queries failing.

Fixes #2222
Fix COUNT(DISTINCT x) queries from getting corrupted in Sqlserver.

Add into the tower of hacks that is the SQL generation and stop breaking
COUNT(DISTINCT foo) style queries. Previously these would be converted
into DISTINCT COUNT(foo) which will give the non-distinct results.