select er.er_pt_type,pt.name
,sum(er.er_emergency_type=1) 'Emergency'
,sum(er.er_emergency_type=2) 'Urgent'
,sum(er.er_emergency_type=3) 'illness'
,sum(er.er_emergency_type=4) 'Non_illness'
,sum(v.pcode in ('uc','aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al')) 'UC'
,sum(v.pcode in ('a2')) 'A2'
,sum(v.pcode in ('a7')) 'A7'
,sum(v.pcode not in ('uc','aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al','a2','a7')) 'Other'
,sum(o.ovstost='54') 'referout'
,sum(o.ovstist='04') 'referin'
,sum(v.income) 'income'
from er_regist er
left join ovst o on o.vn=er.vn
left join vn_stat v on o.vn=v.vn
left join er_pt_type pt on er.er_pt_type=pt.er_pt_type
where er.vstdate between '2012-1-1' and '2012-1-31'
group by er.er_pt_type