select * from (select cf.gid,cf.customername,m.hth,cf.auditdate,cf.bsno,cf.feename, cft.dotyperef,convert(varchar,cf.amount) Y,'' S, cft.dotyperef+'结余:' name,cft.total- (case when(select max(cft2.total) from ch_fee_total cft2 where cft2.customername=cf.customername and cft2.dotype=cf.feetype+2 and cft2.auditdate<=cf.auditdate) is null then 0 else (select max(cft2.total) from ch_fee_total cft2 where cft2.customername=cf.customername and cft2.dotype=cf.feetype+2 and cft2.auditdate<=cf.auditdate) end) jy from ch_fee cf left join ch_fee_total cft on cft.parid=cf.gid left join import_main m on m.contractno=cf.bsno where cf.feestatus in(0,8,9) union all select cf.gid,cf.customername,cf.billno hth,cf.billdate auditdate,'' bsno, '' feename,'实际结算 '+cft.dotyperef dotyperef,'' Y,convert(varchar,cf.amountrmb) S, (select case cft.dotype when 3 then '应收' when 4 then '实收' end) +'结余:' name,(select case max(cft2.total) when null then 0 else max(cft2.total) end from ch_fee_total cft2 where cft2.dotype=cf.billtype and cft2.customername=cf.customername and cft2.auditdate1)) )tt where tt.auditdate>'2013-12-1' order by tt.customername,tt.auditdate,tt.jy,tt.hth select * from ch_fee_total where customername='盛源商行' order by auditdate select feestatus,* from ch_fee where customername='盛源商行' select * from ch_fee_settlement where customername='盛源商行' select * from ch_fee_total cft2 --max(cft2.total where cft2.dotype=1 and cft2.customername='盛源商行' and cft2.auditdate<'2013-11-18 15:33:31.000' --delete from ch_fee_total where dotype=3 and customername='林良威' --delete from ch_fee_settlement where customername='林良威'