SELECT house.villcode,
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2015-10-01',person.birth)/30) = 9 THEN 1 ELSE '' END) AS '9 เดือน',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2015-10-01',person.birth)/30) = 18 THEN 1 ELSE '' END) AS '18 เดือน',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2015-10-01',person.birth)/30) = 30 THEN 1 ELSE '' END) AS '30 เดือน',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2015-10-01',person.birth)/30) = 42 THEN 1 ELSE '' END) AS '42 เดือน'
FROM
person
INNER JOIN house ON person.pcucodeperson = house.pcucode
AND person.hcode = house.hcode
INNER JOIN village ON house.pcucode = village.pcucode
AND village.villcode = house.villcode
WHERE (person.dischargetype is null or person.dischargetype = 9) and SUBSTRING(house.villcode,7,2) !='00'
GROUP BY house.villcode;