Rejigged the SQL construction in order to speed it up, see:

http://dba.stackexchange.com/a/80614/14965