SELECT village.villno as moo 
,count(person.pid) as TOTAL 
,sum(case when person.candobedhomesocial='1' then 1 else 0 end) as 'เตียง 1' 
,sum(case when person.candobedhomesocial='2' then 1 else 0 end) as 'เตียง 2' 
,sum(case when person.candobedhomesocial='3' then 1 else 0 end) as 'เตียง 3' 
,COUNT(*) AS 'รวม'
FROM person 
INNER JOIN house on person.pcucodeperson = house.pcucode and person.hcode = house.hcode 
INNER JOIN village on house.villcode = village.villcode 
WHERE getAgeYearNum (person.birth,CURRENT_DATE) >= 60 
and right(village.villcode,2) !='00' and person.pid not in (select pid from persondeath) GROUP BY moo