CREATE VIEW TOTAL_COORDINADORES(idT, nombreT, TotalCoordinadores)
AS (
  SELECT T.id_tour, T.nombre_tour, COUNT(DISTINCT P.rut_guia)
  FROM participa P
  JOIN tour T ON (T.id_tour = P.id_tour)
  JOIN guia G ON (G.rut_guia = P.rut_guia)
  JOIN categoria C ON (C.id_categoria = P.id_categoria)
  JOIN posee P2 ON (G.rut_guia = P2.rut_guia)
  JOIN asociado A ON (A.id_tour = T.id_tour)
  JOIN lugar L ON (L.id_lugar = A.id_lugar)
  WHERE (
    C.descripcion_categoria = 'Coordinador' AND
    L.nivel = 3 AND
    (SELECT COUNT(rut_guia) FROM posee WHERE (rut_guia = G.rut_guia)) > 3
  )
  GROUP BY (T.id_tour)
);

SELECT nombreT, TotalCoordinadores FROM TOTAL_COORDINADORES ORDER BY TotalCoordinadores DESC;
