/*伝票番号重複用*/
select
	z.cucd,
	m03.cunm,
	z.cuscd,
	m032.spnm,
	z.spktcd,
	m05.spktnm,
	z.vseq,
	to_char(z.dat1, 'yyyy/mm/dd') as dat1,
	to_char(z.dat2, 'yyyy/mm/dd') as dat2,
	to_char(z.idat, 'yyyy/mm/dd') as idat,
	z.amt,
	sum(z.amt) over ( partition by ktktcd ) as t_amt,
	count(*) over ( partition by ktktcd ) as t_vseq,
	z.kflg as ksts,
	z.cuiseq,
	z.viseq
from afm03 m03, afm032 m032, afm05 m05,
	(
	select a.cucd, a.cuscd, a.spktcd, a.vseq,
		a.cuiseq,b.viseq,
		a.dat1,
		a.dat2,
		max(a.idat) idat,
		sum(Calc_Amt(a.cucd,a.pno9,a.cst,1,a.ktktcd,f.cutaxc)) amt,
		case when i.r03='1' and max(b.kflg)=1 then '確認済' else '' end kflg
	from axm994 i,afm05 e,axm99 d,afm03 c,aur32 b,afr31 a
	where a.cls='14' and a.ceslip2='12'
		and a.ktktcd=:ktktcd
		and a.vseq=:vseq
		and a.cucd=:cucd
		and a.cuscd=:cuscd
		and a.ktktcd=d.ktktcd
		and nvl(a.pno9,0)<>0
		and a.dat1>=add_months(d.sdday,-2)
		and a.spktcd=e.ktktcd and e.ktcls<>'02'
		and a.nn1=b.iseq30(+)
		and a.cucd=c.cucd
		and i.cls='KFLG'
		and ((nvl(c.cuhcls,'0')='0' and ((:sts='3') or (:sts<>'3' and b.sbat2>=d.sbat2))
		and (b.sbat>=:sbat or b.sbat=-999) and b.iseq30 is not null) or (nvl(c.cuhcls,'0')='1'))
	group by a.cucd, a.cuscd, a.spktcd, a.vseq,a.cuiseq,b.viseq,a.dat1,a.dat2,i.r03
	union all
	select b.cucd, b.cuscd, b.spktcd, b.vseq,
		null cuiseq,b.viseq,
		b.dat2 dat1,
		b.adat dat2,
		max(b.idat) idat,
		sum(Calc_Amt(b.cucd,abs(nvl(b.tpno,0)),b.icst,1,b.ktktcd,f.cutaxc)) amt,
		case when i.r03='1' and max(b.kflg)=1 then '確認済' else '' end kflg
	from axm994 i,afm05 e,axm99 d,afm03 c,aur32 b
	where b.dcls='1' and b.tcls='02' and b.ent in ('1','3')
		and b.sts=0
		and b.ktktcd=:ktktcd
		and b.vseq=:vseq
		and b.cucd=:cucd
		and b.cuscd=:cuscd
		and b.ktktcd=d.ktktcd
		and abs(nvl(b.tpno,0))<>0
		and b.dat2>=add_months(d.sdday,-2)
		and b.spktcd=e.ktktcd and e.ktcls='02'
		and b.cucd=c.cucd
		and i.cls='KFLG'
		and ((nvl(c.cuhcls,'0')='0' and ((:sts='3') or (:sts<>'3' and b.sbat2>=d.sbat2))
					and (b.sbat>=:sbat or b.sbat=-999) and b.iseq30 is not null) or (nvl(c.cuhcls,'0')='1'))
	group by b.cucd, b.cuscd, b.spktcd, b.vseq,b.viseq,b.dat2,b.adat,i.r03
) z
where z.cucd = m03.cucd(+)
	and z.cucd = m032.cucd(+) and z.cuscd = m032.cuscd(+)
	and z.spktcd = m05.ktktcd(+)
order by z.cucd,z.cuscd,z.spktcd,z.vseq,z.dat1,z.dat2,z.amt
