Original query:

SELECT document.connection_id, document.counterparty_id, percentile_disc(0.5) WITHIN GROUP (ORDER BY anon_2.date - document.due_date) AS anon_1    
FROM (SELECT transaction.id AS id, transaction.connection_id AS connection_id, transaction.created_at AS created_at, transaction.updated_at AS updated_at, transaction.amount AS amount, transaction.currency_code AS cur
rency_code, transaction.date AS date, transaction.deposit_account_id AS deposit_account_id, transaction.document_id AS document_id, transaction.exchange_rate AS exchange_rate, transaction.type AS type, transaction.pay
ment_id AS payment_id, transaction.payment_status AS payment_status, row_number() OVER (PARTITION BY transaction.document_id ORDER BY transaction.date DESC) AS rnk    
FROM transaction    
WHERE transaction.connection_id = 'xero:c866e72a-0de4-46df-a233-925771d303ff' AND transaction.deposit_account_id IS NOT NULL) AS anon_2 JOIN document ON anon_2.document_id = document.id AND anon_2.rnk = 1    
WHERE document.due_date IS NOT NULL AND document.type = 'INVOICE' AND document.counterparty_id = 'xero:c866e72a-0de4-46df-a233-925771d303ff:contact:70af6121-adfa-423a-83dd-78779218eda7' AND document.connection_id = 'x
ero:c866e72a-0de4-46df-a233-925771d303ff' GROUP BY document.connection_id, document.counterparty_id