create table tb4( prcdate [datetime] null, billtype [varchar] (20) null, prcNo [varchar] (20) null, prcName [varchar] (20) null, prcnum [int] null, prcCust [varchar] (50) null )select prcNo,prcName, (select max(tb2.prcdate) from tb4 tb2 where tb2.billtype='进货' and tb2.PrcNo = tb1.prcNo) as lastIndate, DATEDIFF(day, (select max(tb2.prcdate) from tb4 tb2 where tb2.billtype='进货' and tb2.PrcNo = tb1.prcNo) , getdate()) as lastinNum, (select max(tb3.prcdate) from tb4 tb3 where tb3.billtype='销售' and tb3.PrcNo = tb1.prcNo) as lastsaledate, DATEDIFF(day, (select max(tb3.prcdate) from tb4 tb3 where tb3.billtype='销售' and tb3.PrcNo = tb1.prcNo), getdate()) as lastnum, (select abs(isnull(sum(prcnum),0)) from tb4 tb5 where tb5.billtype='销售' and tb5.prcdate> (select max(tb2.prcdate) from tb4 tb2 where tb2.billtype='进货' and tb2.PrcNo = tb5.prcNo) and tb5.PrcNo = tb1.prcNo) as salecountfrom tb4 tb1group by prcNo,prcName