CREATE VIEW TOTAL_TURISTAS(idT, nombreT, TotalTuristas)
AS (
  SELECT T.id_tour, T.nombre_tour, COUNT(R.rut_turista)
  FROM tour T
  JOIN realiza R ON (T.id_tour = R.id_tour)
  JOIN asociado A ON (T.id_tour = A.id_tour)
  JOIN lugar l ON (A.id_lugar = L.id_lugar)
  WHERE (
    L.nivel >= 5 AND
    (A.fecha_llegada BETWEEN '2018-10-01' AND '2018-10-31') AND
    NOT EXISTS (
      SELECT id_enfermedad
      FROM tiene_enfermedad T2
      WHERE (T2.rut_turista = R.rut_turista AND
        (T2.id_enfermedad = 1 OR T2.id_enfermedad = 3)
      )
    )
  )
  GROUP BY (T.id_tour)
);

SELECT nombreT, TotalTuristas FROM TOTAL_TURISTAS ORDER BY TotalTuristas DESC;
