fixed #53, rewrote query to get rid of the PostgreSQL error with having ...

...clause