SELECT RPAO.R_PERS_ACCOUNT_ID, MAX(RBS.CREATE_DATE)
FROM R_BASE_TRANS RBS
JOIN R_PERS_ACC_OPERATION RPAO ON RBS.R_BASE_TRANS_ID = RPAO.R_BASE_TRANS_ID
WHERE RBS.CREATE_DATE BETWEEN TO_DATE('01.03.2020', 'DD.MM.YYYY') AND TO_DATE('31.12.2020', 'DD.MM.YYYY')
AND RBS.M_BASE_TRANS_TYPE_ID NOT IN 26
AND ROWNUM < 100
GROUP BY RPAO.R_PERS_ACCOUNT_ID),
TAX_QUERY 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)
FROM R_PERS_ACCOUNT PA
JOIN NESTED_TABLE NT ON NT.R_PERS_ACCOUNT_ID = PA.R_PERS_ACCOUNT_ID
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 IS_CHARGE_FINE = 0
AND TRUNC(OP.ACTUAL_DATE, 'FMDD') <= TO_DATE('15-05-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
HAVING SUM(OP.AMOUNT) < 0)