SELECT
person.pcucodeperson,
person.pid,
person.prename,
person.fname,
person.lname,
person.birth,
person.idcard,
visit.visitdate,
visitdiag.diagcode
FROM
person
INNER JOIN visit ON visit.pcucodeperson = person.pcucodeperson AND visit.pid = person.pid
INNER JOIN visitdiag ON visitdiag.pcucode = visit.pcucode AND visitdiag.visitno = visit.visitno
WHERE person.typelive IN ('1','3') AND person.dischargetype<>'1' AND person.occupa IN ('001') AND visitdiag.diagcode NOT IN ('z10.0')
 AND visit.visitdate BETWEEN '20131001' AND '20140930'
GROUP BY person.pid;