select m.HTH,t1.* into #t from (select gid,bsno,customername,feetype,feename, case feetype when 1 then amount else 0 end ys,case feetype when 2 then amount else 0 end yf,0 y,0 ss,0 sf,0 s, case feetype when 1 then convert(varchar,amount) else '' end ys_ref, case feetype when 2 then convert(varchar,amount) else '' end yf_ref,'' y_ref,'' ss_ref,'' sf_ref,'' s_ref, enterdate [feedate],remark from ch_fee where feestatus in(0,8,9) union all select gid,bsno,customername,billstatus feetype,feename, 0 ys,0 yf,0 y, case billstatus when 1 then amount else 0 end ss,case billstatus when 2 then amount else 0 end sf,0 s, '' ys_ref,'' yf_ref,'' y_ref,case billstatus when 1 then convert(varchar,amount) else '' end ss_ref, case billstatus when 2 then convert(varchar,amount) else '' end sf_ref,'' s_ref, createtime [feedate],remark from ch_fee_do where (isdeleted is null or isdeleted<>1) ) t1 left join import_main m on m.contractno=t1.bsno order by t1.bsno,t1.[feedate] select gid,bsno,hth,customername,feetype,feename,ys,yf,y,ss,sf,s,ys_ref,yf_ref,y_ref ,ss_ref,sf_ref,s_ref,feedate,remark from #t union select '','',#T.hth,'接单时间:'+convert(varchar,M.creattime,120),3,'小计' feename, 0,0,0,0,0,0,convert(varchar,sum(ys)),convert(varchar,sum(yf)),convert(varchar,sum(ys)-sum(yf)), convert(varchar,sum(ss)), convert(varchar,sum(sf)), convert(varchar,sum(ss)-sum(sf)), getdate(),'' from #t left join import_main m on m.contractno=#t.bsno group by #t.hth,creattime order by hth,feetype drop table #t