Postgresql Aggregate Functions Cannot Be Nested Ifs Javascript