SELECT person.pid
,CONCAT_WS('-',substring(idcard,1,1),substring(idcard,2,4),substring(idcard,6,5),substring(idcard,11,2),substring(idcard,13,1))AS 'เลขบัตรประชาชน'
,CONCAT(ctitle.titlename,' ',person.fname,' ',person.lname) AS 'ชื่อ-สกุล'
,CONCAT(DATE_FORMAT(person.birth,'%d-%m-'),DATE_FORMAT(person.birth,'%Y')+543) AS 'วันเดือนปีเกิด'
,YEAR( FROM_DAYS( DATEDIFF( NOW( ) ,person.birth ) ) ) AS 'อายุ'
,person.hnomoi AS 'บ้านเลขที่'
,SUBSTRING(house.villcode,7,2) AS 'หมู่ที่'
,visit.visitdate AS 'วันที่รับกลับ'
,visit.receivepatient AS 'เหตุผลที่รับผู้ป่วยมา'
,visit.receivefromhos AS 'รับมาจากโรงพยาบาล'
FROM person
LEFT JOIN ctitle ON person.prename = ctitle.titlecode
LEFT JOIN persondeath ON person.pcucodeperson = persondeath.pcucodeperson AND person.pid = persondeath.pid
LEFT JOIN house ON house.pcucode = person.pcucodeperson AND house.hcode = person.hcode
LEFT JOIN village ON village.pcucode = house.pcucode AND village.villcode = house.villcode
LEFT JOIN visit ON person.pid=visit.pid AND person.pcucodeperson=visit.pcucodeperson
WHERE persondeath.pid IS NULL
AND visit.receivepatient<>'00' 
AND visit.visitdate BETWEEN '2014-10-01' AND '2015-09-30'
AND person.typelive in ('0','1','3')
AND right((house.villcode),2) != 00
ORDER BY villno,hnomoi*1;