Original query:

select d.connection_id,
       d.counterparty_id,
       percentile_disc(0.5) within group (order by t.date - d.due_date) as anon_1
from document as d
cross join lateral (
    select t.date
    from transaction as t
    where t.document_id = d.id
      and t.connection_id = d.connection_id
      and t.deposit_account_id is not null
    order by t.date desc
    limit 1) as t
where d.due_date is not null
  and d.type = 'INVOICE'
  and d.counterparty_id = 'xero:c866e72a-0de4-46df-a233-925771d303ff:contact:70af6121-adfa-423a-83dd-78779218eda7'
  and d.connection_id = 'xero:c866e72a-0de4-46df-a233-925771d303ff'
group by d.connection_id, d.counterparty_id