Fix queries for Oracle compatibility

They were using a MySQL only feature in the group by
to prevent duplicates. Do the duplicate filtering
after the database query to keep a single compatible query.
Merge pull request #4589 from dballesteros7/DBS-DBS-DBS

Fix queries for Oracle compatibility