select l.hospcode,concat(p1.`NAME`,'',p1.LNAME)as fullname,l.pid as labor_pid,a.hospcode as prenatal_hospcode,a.pid as prenatal_pid,l.bhosp,l.gravida as labor_gravida,a.gravida as prenatal_gravida,l.bdate,a.edc
from hdc.labor l
left outer join hdc.person p1 on p1.hospcode=l.hospcode and p1.pid=l.PID
left outer join (select p2.cid,a.* from hdc.prenatal a
left outer join hdc.person p2 on p2.hospcode=a.hospcode and p2.pid=a.PID ) a on a.cid=p1.cid
left outer join hdc.chospital c on c.hoscode=l.hospcode
where l.bdate between @start_d AND @end_d and l.gravida<> a.gravida
and (timestampdiff(month,a.edc,l.bdate )<='3' )
group by l.hospcode,p1.cid
order by l.hospcode