with as insert

  with  

 a as(select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'B01%' ),
 b as ( select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'H0%'),
 c as (select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'B02%'),
 d as ( select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'B04%' ),
 e as (select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'B05%' ),
 f as ( select distinct pcode,matid,matgroup,matmemo from ps where matgroup like 'B06%' )
  insert into prod
select a.pcode,a.matid bottle  ,b.matid beverage  ,c.matid cap, d.matid closure, e.matid label, f.matid box  from a left   join b on a.pcode=b.pcode 
   left join e on a.pcode=e.pcode 
   left join f on a.pcode=f.pcode 
   left join d on a.pcode=d.pcode 
   left   join c on a.pcode=c.pcode 

你可能感兴趣的:(SQLServer)