 SELECT house.villcode,
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2013-10-01',person.birth)/30) <= 35.99 THEN 1 ELSE ''  END) AS '0-2ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2013-10-01',person.birth)/30) <= 47.99 THEN 1 ELSE ''  END) AS '0-3ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2013-10-01',person.birth)/30) BETWEEN 36 AND 71.99 THEN 1 ELSE ''  END) AS '3-5ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2013-10-01',person.birth)/30) BETWEEN 72 AND 143.99 THEN 1 ELSE ''  END) AS '6-12ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2013-10-01') >= 15 THEN 1 ELSE ''  END) AS '15ปีขึ้นไป',
SUM(CASE WHEN person.sex='2' AND person.typelive IN ('1','3') AND GetAgeYearNum(person.birth,'2013-10-01') BETWEEN 30 AND 59 THEN 1 ELSE ''  END) AS 'หญิง30-60ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2013-10-01') >= 60 THEN 1 ELSE ''  END) AS '60ปีขึ้นไป',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2013-10-01') between 15 and 34 THEN 1 ELSE ''  END) AS '15_34',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2013-10-01') between 35 and 59 THEN 1 ELSE ''  END) AS '35_59'
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;