WITH NESTED_TABLE AS (SELECT TP.IIN_BIN,
PA.R_PERS_ACCOUNT_ID,
PA.CLOSE_DATE,
KBK.KBK_CODE,
ORG.CODE_NK,
ORG.CODE_TPK,
OP.M_OPERATION_TYPE_ID,
PA.OPEN_DATE,
SUM(OP.AMOUNT),
LAST_DAY(OP.ACTUAL_DATE)
FROM R_PERS_ACCOUNT PA
JOIN R_TAX_PAYER TP ON TP.R_TAX_PAYER_ID = PA.R_TAX_PAYER_ID
JOIN R_PERS_ACC_OPERATION OP ON OP.R_PERS_ACCOUNT_ID = PA.R_PERS_ACCOUNT_ID
JOIN M_KBK KBK ON KBK.M_KBK_ID = PA.M_KBK_ID
JOIN M_TAX_ORG ORG ON ORG.M_TAX_ORG_ID = PA.M_TAX_ORG_ID
WHERE PA.R_PERS_ACCOUNT_ID IN (16616882)
AND IS_CHARGE_FINE = 0
AND OP.ACTUAL_DATE < TO_DATE('31.12.2020', 'DD.MM.YYYY')
AND OP.M_OPERATION_TYPE_ID = 1
GROUP BY TP.IIN_BIN, PA.R_PERS_ACCOUNT_ID, PA.CLOSE_DATE, KBK.KBK_CODE, OP.M_OPERATION_TYPE_ID,
ORG.CODE_NK,
ORG.CODE_TPK, PA.OPEN_DATE, LAST_DAY(OP.ACTUAL_DATE), OP.AMOUNT
HAVING SUM(OP.AMOUNT) < 0)
SELECT TP.IIN_BIN,
PA.R_PERS_ACCOUNT_ID,
PA.CLOSE_DATE,
KBK.KBK_CODE,
ORG.CODE_NK,
ORG.CODE_TPK,
OP.M_OPERATION_TYPE_ID,
PA.OPEN_DATE,
(OP.AMOUNT) AS SUM,
LAST_DAY(OP.ACTUAL_DATE) AS ERROR_POENA
FROM R_PERS_ACCOUNT PA
JOIN NESTED_TABLE TQ ON TQ.R_PERS_ACCOUNT_ID = PA.R_PERS_ACCOUNT_ID
JOIN R_TAX_PAYER TP ON PA.R_TAX_PAYER_ID = TP.R_TAX_PAYER_ID
JOIN R_PERS_ACC_OPERATION OP ON OP.R_PERS_ACCOUNT_ID = PA.R_PERS_ACCOUNT_ID
JOIN M_KBK KBK ON KBK.M_KBK_ID = PA.M_KBK_ID
JOIN M_TAX_ORG ORG ON ORG.M_TAX_ORG_ID = PA.M_TAX_ORG_ID
WHERE PA.R_PERS_ACCOUNT_ID IN TQ.R_PERS_ACCOUNT_ID
AND IS_CHARGE_FINE = 0
AND OP.M_OPERATION_TYPE_ID = 2
AND OP.ACTUAL_DATE < TO_DATE('31.12.2020', 'DD.MM.YYYY')
AND OP.AMOUNT >= 0
GROUP BY TP.IIN_BIN, PA.R_PERS_ACCOUNT_ID, PA.CLOSE_DATE, KBK.KBK_CODE, OP.M_OPERATION_TYPE_ID, ORG.CODE_NK,
ORG.CODE_TPK, PA.OPEN_DATE, LAST_DAY(OP.ACTUAL_DATE), OP.AMOUNT;