SELECT house.villcode,
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2012-12-31',person.birth)/30) <= 6 THEN 1 ELSE '' END) AS '0-6เดือน',
SUM(CASE WHEN person.typelive in ('1','3') AND person.birth between '2011-12-01' and '2011-12-31' THEN 1 ELSE '' END) AS 'ครบ1ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2012-12-31',person.birth)/30) <= 35.99 THEN 1 ELSE '' END) AS '0-2ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND person.birth between '2010-12-01' and '2010-12-31' THEN 1 ELSE '' END) AS 'ครบ2ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2012-12-31',person.birth)/30) <= 47.99 THEN 1 ELSE '' END) AS '0-3ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND person.birth between '2009-12-01' and '2009-12-31' THEN 1 ELSE '' END) AS 'ครบ3ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2012-12-31',person.birth)/30) BETWEEN 36 AND 71.99 THEN 1 ELSE '' END) AS '3-5ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND person.birth between '2007-12-01' and '2007-12-31' THEN 1 ELSE '' END) AS 'ครบ5ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND ROUND(DATEDIFF('2012-12-31',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,'2012-12-31') >= 15 THEN 1 ELSE '' END) AS '15ปีขึ้นไป',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2012-12-31') >= 35 THEN 1 ELSE '' END) AS '35ปีขึ้นไป',
SUM(CASE WHEN person.sex='2' AND person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2012-12-31') BETWEEN 30 AND 59.99 THEN 1 ELSE '' END) AS 'หญิง30-60ปี',
SUM(CASE WHEN person.typelive in ('1','3') AND GetAgeYearNum(person.birth,'2012-12-31') >= 60 THEN 1 ELSE '' END) AS '60ปีขึ้นไป'
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;