Загрузка данных


insert into "transaction" (
    id,
    operation_id,
    debit_account_id,
    credit_account_id,
    value,
    version,
    comment
)
select
    nextval('BACK_OFFICE.TRANSACTION_SEQUENCE'),
    mnem.operation_id,

    case
        when mnem.death_fact then da.id
        else ca.id
    end as debit_account_id,

    case
        when mnem.death_fact then ca.id
        else da.id
    end as credit_account_id,

    mnem.payment_value,
    current_timestamp,
    cast(mnem.id as varchar)
from (
    select
        o.operation_id,
        o.death_fact,
        rd.id,
        rd.sharer_id,
        rdb.account_type_id,
        sum(rdb.value) as payment_value
    from operation o
    join back_office.rops_decisions rd
        on rd.id = o.rops_decisions
    join back_office.rops_decisions_balance rdb
        on rd.id = rdb.rops_decisions_id
    group by
        o.operation_id,
        o.death_fact,
        rd.id,
        rd.sharer_id,
        rdb.account_type_id
) mnem
join lateral (
    select
        da.id
    from back_office.account da
    where da.owner_sharer_id = mnem.sharer_id
      and da.account_type_id = mnem.account_type_id
) da on true
join lateral (
    select
        a.id
    from back_office.account a
    join back_office.account_type act
        on act.id = a.account_type_id
    where act.mnemonics in ('Р ОПС')
) ca on true;