select max(cuiseq) as cuiseq,count(distinct cuiseq) as cnt,ktcls
from (
	select /* 物流ｾﾝﾀｰ以外 */
				a.cuiseq,e.ktcls
	from 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 (:cuiseq is null or a.cuiseq = :cuiseq)
		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 ((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'))
	union all
	select /* 物流ｾﾝﾀｰ */
				b.viseq cuiseq,e.ktcls
	from 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 (:viseq is null or b.viseq = :viseq)
		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 ((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 ktcls
