1.OPD
select r.vn,r.hn,r.refer_date,r.hospcode,r.refer_point
,ifnull(r.pdx,if(r.pdx=' ',v.pdx,r.pdx)) as pdx
from referout r
left join vn_stat v on r.vn=v.vn
where r.refer_date between '2010-1-1' and '2010-1-31'
and r.refer_point<>'IPD'
2.IPD
select r.vn,r.hn,r.refer_date,r.hospcode,r.refer_point
,ifnull(r.pdx,if(r.pdx=' ',a.pdx,r.pdx)) as pdx
from referout r
left join an_stat a on r.vn=a.an
where r.refer_date between '2010-1-1' and '2010-1-31'
and r.refer_point='IPD'
น่าจะประมาณนี้ ถ้าคุณลงข้อมูล refer กันครบ