--------------------------------------------------------------------------------
-----------------------------------   COLOCACIONES NETAS SDA
--------------------------------------------------------------------------------
  
DROP TABLE IF EXISTS d_mdl_vpc_disc.HM_COLNETA_DETALLE   
CREATE TABLE d_mdl_vpc_disc.HM_COLNETA_DETALLE
WITH ( format = 'Parquet', 
         parquet_compression = 'SNAPPY', 
         partitioned_by = ARRAY['p_periodo'],
         external_location= 's3://sagemaker-us-east-1-058528764918/vpc/aceptacion/athena_2/HM_COLNETA_DETALLE/'
       )
AS (
    SELECT substr(replace(cast(fecha_desemb_dt as varchar), '-', ''), 1, 6) periodo_desembolso,
               substr(replace(cast(fecha_solicitud_dt as varchar), '-', ''), 1, 6) periodo_solicitud, 
               numero_documento_val,
               min(fecha_desemb_dt) fecha_desemb_dt,
               min(fecha_solicitud_dt) fecha_solicitud_dt,
               max(CASE WHEN colocacion_neta > 0 then 1 else 0 end) flg_desembolso,
               max(colocacion_neta) colocacion_neta,
               max(tea_aprobada_amt) tea_aprobada_amt,
               max(fecinformacion_dt) fecinformacion_dt,
               substr(replace(cast(fecha_desemb_dt as varchar), '-', ''), 1, 6) p_periodo
        FROM (
            select ZZ.*, 
             ROW_NUMBER() OVER(PARTITION BY ZZ.credito_cd ORDER BY ZZ.fecha_solicitud_dt ASC, ZZ.periodo_val ASC, ZZ.fecinformacion_dt ASC) ORDEN
             FROM (
                    SELECT CC.*
                    FROM e_perm_aws.t_fact_vpc_colnetas CC
                    WHERE 1 = 1
                    AND CC.colocacion_neta > 0
                    AND CC.tipo_colocacion NOT LIKE '%Cima%'
                    AND CC.fecinformacion_dt in (
                        select fecinformacion_dt from (
                            SELECT periodo_val,
                            max(fecinformacion_dt) fecinformacion_dt
                            FROM e_perm_aws.t_fact_vpc_colnetas
                            GROUP BY periodo_val
                        )
                    )
            ) ZZ
        ) AA
        WHERE AA.ORDEN = 1
        GROUP BY substr(replace(cast(fecha_desemb_dt as varchar), '-', ''), 1, 6),
                 substr(replace(cast(fecha_solicitud_dt as varchar), '-', ''), 1, 6),
                 numero_documento_val
)



SELECT periodo_desembolso, COUNT(1) 
FROM d_mdl_vpc_disc.HM_COLNETA_DETALLE 
GROUP BY periodo_desembolso

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