drop table if exists {p_i07tbl1};
/*peg_end*/


/**************************
     create temp
**************************/
create table {p_i07tbl1}
select i07.*, 
       sum(i07.p06) as p06tot 
from i07
where p06<>0
   && p010<>'' 
GROUP BY i07.p01, i07.p02, i07.p04   ;
/*peg_end*/

update {p_i07tbl1} set nr01=0;
/*peg_end*/
  
update {p_i07tbl1} set nr01=peg_new_nr01('i01', 1);
/*peg_end*/
  
/****************
    i01
*****************/    
INSERT INTO i01
(nr01, p01, p02, p03, p04, p013, p011, p022, p05, p012, p610, p0601, pd01, pd101, 
remdate, remtime, remuser, remfdate, remftime, remfuser)
SELECT i07.nr01 as nr01, 
       i07.p02 as p01, 
       i07.vp02 as p02, 
       i07.p06tot as p03, 
       i07.p04 as p04, 
       '{odbcdtos(np_dt)}' as p013, 
       round(i07.p06tot*i07.p04, 2) as p011, 
       round(i07.p06tot*i07.p04, 2) as p022, 
       {np_kk} as p05, 
       1 as p012, 
       i07.p01 as p610, 
       concat('{peg_str1}', ' Lots') as p0601, 
       '{peg_str2}_l' as pd01, 
       'i07' as pd101, 
       
       curdate() as remdate, 
       curtime() as remtime, 
       '{user_pswd}' as remuser, 
       curdate() as remfdate, 
       curtime() as remftime, 
       '{user_pswd}' as remfuser
FROM {p_i07tbl1} as i07;
/*peg_end*/   

/****************
    i38
*****************/    
INSERT INTO i38
(nr01, p01, p02, p010, p04, 
remdate, remtime, remuser, remfdate, remftime, remfuser)
SELECT peg_new_nr01('i38', 1)  as nr01, 
       {p_i07tbl1}.nr01 as p01, 
       i07.p010 as p02, 
       1 as p010, 
       i07.p06 as p04, 

       curdate() as remdate, 
       curtime() as remtime, 
       '{user_pswd}' as remuser, 
       curdate() as remfdate, 
       curtime() as remftime, 
       '{user_pswd}' as remfuser
FROM {p_i07tbl1}, i07
WHERE {p_i07tbl1}.p01=i07.p01
   && {p_i07tbl1}.p02=i07.p02
   && {p_i07tbl1}.p04=i07.p04
   && i07.p06<>0
   && i07.p010<>'' ;
/*peg_end*/

drop table if exists {p_i07tbl1};
/*peg_end*/
