How to replace subqueries containing aggregate functions in PostgreSQL with Windows functions?