WITH target_accounts AS MATERIALIZED (
SELECT
a.id AS account_id,
b.total_credit - b.total_debit AS current_balance
FROM back_office.account a
JOIN back_office.balance b
ON b.account_id = a.id
AND current_date BETWEEN b.start_date AND b.end_date
WHERE a.account_type_id = 62 -- НВ ПП ОПС
AND b.total_credit - b.total_debit > 0
LIMIT 5
)
SELECT
a.account_id,
a.current_balance,
charges.decision_id,
charges.decision_number,
charges.charged_value
FROM target_accounts a
LEFT JOIN LATERAL (
SELECT
d.id AS decision_id,
d.number AS decision_number,
sum(t.value) AS charged_value
FROM back_office.transaction t
JOIN back_office.operation o
ON o.id = t.operation_id
JOIN back_office.ops_assignee_decision d
ON d.id = o.ops_assignee_decision_id
WHERE t.credit_account_id = a.account_id
AND o.approved IS NOT NULL
AND o.deleted IS NULL
GROUP BY d.id, d.number
) charges ON true
ORDER BY a.account_id, charges.decision_id;