select hash, count(*), count(distinct siv.date_nop), count(distinct d."_plannedDueDate"), count(distinct GREATEST(siv.date_nop,d."_plannedDueDate")) from elma.deals_services siv left outer join elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement)) left outer join elma.deals d on (d.__id = ANY(siv.deal)) where d.__status_status in(5,6) group by hash having count(distinct GREATEST(siv.date_nop,d."_plannedDueDate")) > 1 select hash, siv.type, count(*), count(distinct siv.date_nop), count(distinct d."_plannedDueDate"), count(distinct GREATEST(siv.date_nop,d."_plannedDueDate")) from elma.deals_services siv left outer join elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement)) left outer join elma.deals d on (d.__id = ANY(siv.deal)) where d.__status_status in(5,6) AND siv.type=2 group by hash, siv.type having count(distinct GREATEST(siv.date_nop,d."_plannedDueDate")) > 1 --