Modified SQL to run on Oracle and PostgreSQL (mostly added explicit casts)