SELECT 
    m.dpto_snc as DPTO,
    m.entidad_id as EID,
    COALESCE(e.nombre, 'No existe nombre') AS MUNICIPIO_SIGEM,
    m.dist_snc as DIST_SNC,
    COALESCE(r.nom_dist, 'No existe nom_dist') AS DISTRITO_SNC
FROM public.snc_catalog_mapping m
LEFT JOIN public.snc_raw_distritos r 
    ON m.dpto_snc = r.cod_dpto AND m.dist_snc = r.cod_dist
LEFT JOIN LATERAL (
    SELECT nombre FROM dblink('host=192.168.1.254 user=postgres password=x25yvaga2017 dbname=sigemweb',
    'SELECT nombre FROM public.entidades WHERE entidad = ' || m.entidad_id::text)
    AS t(nombre text)
) e ON true
ORDER BY m.dpto_snc, m.entidad_id;
