SELECT trim(to_char(date_trunc('month', ao.invoice_date), 'Month')) || to_char(date_trunc('month', ao.invoice_date), ' YYYY') AS "Month"
    ,ca.code AS "Customer Account code"
    ,ca.description AS "Customer Account description"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'DEBIT'
                    THEN ao.amount
                ELSE 0
                END), '99999999990.00') AS "Amount DEBIT"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'CREDIT'
                    THEN ao.amount
                ELSE 0
                END), '99999999990.00') AS "Amount CREDIT"
    ,to_char(sum(CASE 
                WHEN ao.transaction_category = 'DEBIT'
                    THEN ao.amount
                ELSE - ao.amount
                END), '99999999990.00') AS "Balance"
FROM crm_seller s
    INNER JOIN crm_customer c ON c.seller_id = s.id
    INNER JOIN ar_customer_account ca ON ca.customer_id = c.id
    INNER JOIN ar_account_operation ao ON ao.customer_account_id = ca.id
WHERE ao.invoice_date IS NOT NULL
    AND ao.invoice_date > (date_trunc('month', CURRENT_DATE) - CAST(:MONTH_INTERVAL || ' month' AS INTERVAL))
    AND (
        ca.code ilike '%' || :SEARCH_CRITERION || '%'
        OR ca.description ilike '%' || :SEARCH_CRITERION || '%'
        )
GROUP BY date_trunc('month', ao.invoice_date)
    ,ca.code
    ,ca.description
ORDER BY date_trunc('month', ao.invoice_date) DESC
    ,ca.code