SELECT RIGHT(house.villcode,2) as หมู่ที่, house.villcode,
SUM(CASE WHEN person.sex='1' THEN 1 ELSE 0 END) AS ชาย,
SUM(CASE WHEN person.sex='2' THEN 1 ELSE 0 END) AS หญิง,
SUM(CASE WHEN person.sex='1' OR person.sex='2' THEN 1 ELSE 0 END) AS รวม
FROM
person
INNER JOIN house ON person.hcode = house.hcode
WHERE
RIGHT(house.villcode,2) <> "00" and person.typelive = ("1" or "3")
GROUP BY house.villcode
