SELECT
person.pid,
IFNULL(ctitle.titlename,person.prename) AS คำนำ,
person.fname AS ชื่อ,
person.lname AS สกุล,
person.birth AS 'วันเดือนปี เกิด',
(getAgeYearNum(birth,CURDATE())) AS'ปี',
(getAgeMonthNum(birth,CURDATE()))AS' เดือน ',
(getAgeDayNum(birth,CURDATE()))AS' วัน',
house.hno AS บ้านเลขที่,
person.mumoi AS 'หมู่ที่',
#RIGHT(house.villcode,2) AS 'หมู่ที่',
MAX(IF(visitepi.vaccinecode ='dTC',visitepi.dateepi,'-')) AS dTC
FROM person 
INNER JOIN house ON person.pcucodeperson = house.pcucode AND person.hcode = house.hcode
LEFT JOIN ctitle  ON person.prename = ctitle.titlecode
LEFT JOIN visitepi  ON person.pid = visitepi.pid AND person.pcucodeperson = visitepi.pcucodeperson
WHERE (getAgeYearNum(birth,CURDATE())BETWEEN '20' AND '50') 
AND person.typelive IN ('1','3')
AND((person.dischargetype IS NULL) OR (person.dischargetype != '1'))
AND nation='99'
GROUP BY person.pid
ORDER BY mumoi;