SELECT 
        A.FECPROCESO, TRIM(A.NUMRUC) NUMRUC, 
        MAX(S.CODUNICOCLI) cod_unico_val,
        MAX(CASE WHEN S.ORDER_CODSBS = 1 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_1,
        MAX(CASE WHEN S.ORDER_CODSBS = 2 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_2,
        MAX(CASE WHEN S.ORDER_CODSBS = 3 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_3,
        MAX(CASE WHEN S.ORDER_CODSBS = 4 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_4,
        MAX(CASE WHEN S.ORDER_CODSBS = 5 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_5,
        MAX(CASE WHEN S.ORDER_CODSBS = 6 THEN S.CODSBS ELSE NULL END ) cod_sbs_empresa_6,
        MAX(CASE WHEN R.RRLL_CODSBS = 1 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_1,
        MAX(CASE WHEN R.RRLL_CODSBS = 2 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_2,
        MAX(CASE WHEN R.RRLL_CODSBS = 3 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_3,
        MAX(CASE WHEN R.RRLL_CODSBS = 4 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_4,
        MAX(CASE WHEN R.RRLL_CODSBS = 5 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_5,
        MAX(CASE WHEN R.RRLL_CODSBS = 6 THEN R.CODSBS ELSE NULL END ) cod_sbs_rrll_6

        FROM ............V_REP_LEGALES_SUNAT_HIST A
        LEFT JOIN (
            SELECT ROW_NUMBER() OVER (PARTITION BY  (
                CASE WHEN NUMDOCTRIB LIKE '.' OR  NUMDOCTRIB LIKE '' OR NUMDOCTRIB IS NULL THEN NUMDOCTRIB_TRDT ELSE NUMDOCTRIB END)
                ORDER BY NUMDOCTRIB DESC, TIPPERSONA ASC, CODSBS
            ) ORDER_CODSBS,
              CODSBS,  
              NUMDOCTRIB_TRDT, 
              NUMDOCTRIB,
              CODDOC_TRDT,
              CODDOC, 
              CODUNICOCLI
              FROM ............V_RSK_FCT_MAEPERSONA_RCC
        ) S
        ON A.NUMRUC = (CASE WHEN S.NUMDOCTRIB LIKE '.' OR  S.NUMDOCTRIB LIKE '' OR S.NUMDOCTRIB IS NULL THEN S.NUMDOCTRIB_TRDT ELSE S.NUMDOCTRIB END)
        LEFT JOIN (
            SELECT ROW_NUMBER() OVER (PARTITION BY (
                CASE WHEN CODDOC LIKE '.' OR  CODDOC LIKE '' OR CODDOC IS NULL THEN CODDOC_TRDT ELSE CODDOC END)
                ORDER BY NUMDOCTRIB DESC, TIPPERSONA ASC, CODSBS
            ) RRLL_CODSBS,
             CODSBS,  
             NUMDOCTRIB_TRDT, 
            NUMDOCTRIB, 
            CODDOC_TRDT, 
            CODDOC, 
            CODUNICOCLI
            FROM ............V_RSK_FCT_MAEPERSONA_RCC
            WHERE CODDOC NOT LIKE '.' OR CODDOC_TRDT NOT LIKE '.' 
        ) R
        ON A.CODDOC =  (CASE WHEN R.CODDOC LIKE '.' OR  R.CODDOC LIKE '' OR R.CODDOC IS NULL THEN R.CODDOC_TRDT ELSE R.CODDOC END)
        WHERE 1 = 1
        AND A.ESTADO = 0
        GROUP BY A.FECPROCESO,  TRIM(A.NUMRUC)

Add a code snippet to your website: www.paste.org