with moving as (
select
side.account,
side.direction,
et.operation_sum
from back_office.eps_transaction et
join back_office.eps_transaction_source src
on src.id = et.eps_transaction_source_id
join ourpension.eps e
on e.id = et.eps_id
join ourpension.eps_detail ed
on ed.eps_id = e.id
cross join lateral (
values
(ed.account_dt, 'DT'),
(ed.account_ct, 'CT')
) as side(account, direction)
where e.service_type = 'NPO'
and e.periodicity in (1, 2)
and et.oper_date >= date '2026-09-01'
and et.oper_date < date '2026-10-01'
and side.account in (
'60301', '60302', '60322', '60323'
)
)
select
a.account,
count(m.account) as source_rows,
coalesce(
sum(m.operation_sum) filter (
where m.direction = 'DT'
), 0
)
- coalesce(
sum(m.operation_sum) filter (
where m.direction = 'CT'
), 0
) as sum_pu
from (
values
('60301'),
('60302'),
('60322'),
('60323')
) as a(account)
left join moving m
on m.account = a.account
group by a.account
order by a.account