insert into afw851 (
	wseq, cls, ktktcd,
	cucd, dat1, key1, key2
)
select :wseq, 'o', :ktktcd,
	a.cucd, a.adat, a.vseq, a.viseq
from (
	select distinct a.cucd, a.adat, a.vseq,a.viseq
		from axm99 d,afr3123 c,afm03 b,aur32 a
		where a.ktktcd=:ktktcd and a.dcls='1'
			and a.tcls=:tcls and a.psts=:psts
			and a.cucd=:cucd and a.cuscd=:cuscd
			and (:h_chgcd is null or a.chgcd=:h_chgcd)
			and (:h_sadat is null or a.adat>=to_date(:h_sadat,'yyyy/mm/dd'))
			and (:h_eadat is null or a.adat<=to_date(:h_eadat,'yyyy/mm/dd'))
			and ((:hvseq=0 and a.hvseq is null) or (:hvseq=1 and a.hvseq is not null))
			and a.cucd=b.cucd
			and a.piseq=c.iseq(+)
			and a.ktktcd=d.ktktcd
			and (a.psts=0 or (a.psts=-1 and a.adat>=add_months(d.sdday,-2)))
		order by a.cucd, a.adat, a.vseq,a.viseq
) a
