'ERROR IN POSTGRESQL: aggregate function calls cannot be nested

I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

sum(
    case 
        when sum(cs.valor + p.valor) <= 89 then 5 
        when sum(cs.valor + p.valor) <= 99 then 10 
        when sum(cs.valor + p.valor) <= 109 then 15
        when sum(cs.valor + p.valor) <= 119 then 20
        when sum(cs.valor + p.valor) > 120 then 25
        else 0 end
    +
    case
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >= 6 then 5 
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >= 12 then 10 
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >= 18 then 15
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >= 24 then 20
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >= 30 then 25
        when (DATE_PART('year', current_date) - DATE_PART('year', c.data_cadastro)) * 12  + (DATE_PART('month', current_date) - DATE_PART('month', c.data_cadastro)) >  36 then 30
        else 0 end
    +
    ROUND(((ROUND(((CAST(count(case when date(fa.data_pagamento) <= date(fa.data_vencimento) then fa.id_fatura end) AS DECIMAL)*100)/(CAST(count(fa.id_fatura) AS DECIMAL))),2)*50)/100),2)
)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source