select x.*,
	ceil(rnum / :lcnt) as pgno,
	0 chkval,
	max(rnum) over() as maxnum
from (
	select
		ROW_NUMBER() OVER (ORDER BY a.cucd,a.cuscd,
			decode(d.cls,0,null,a.vseq), decode(d.cls,0,null,a.viseq),
			a.tcls,decode(d.cls,0,decode(a.hvseq,null,0,1),null)) as rnum,
		a.cucd,
		b.cunm,
		a.cuscd,
		c.spnm,
		a.tcls,
		decode(a.tcls,'01','納品','02','返品','03','値引') as tclsnm,
		decode(a.hvseq,null,0,1) as hvseq,
		decode(a.hvseq,null,null,'直送') as hvseqnm,
		decode(d.cls,0,null,to_char(a.dat2,'yyyy/mm/dd')) dat2,
		decode(d.cls,0,null,to_char(a.adat,'yyyy/mm/dd')) adat,
		decode(nvl(e.cls1,'0'),'1',nvl(b.cudenp1,b.cudenp2),b.cudenp2) as cudenp,
		decode(nvl(e.cls1,'0'),'1',nvl(b.cudenp1,b.cudenp2),b.cudenp2) as cudenpnm,
		decode(d.cls,0,null,a.vseq) as vseq,
		decode(d.cls,0,null,a.viseq) as viseq,
		count(distinct a.vseq||a.viseq) as vcnt,
		a.psts,
		decode(nvl(e.cls1,'0'),'1',nvl(f.scls7,g.scls7),g.scls7) as scls7,
		:defprno as prno
	from axm99 h,afm90 g,afm90 f,afr3123 e,(select nvl(:chk_grpkbn, 0) as cls from dual) d,afm032 c,afm03 b,aur32 a
	where a.ktktcd=:ktktcd
		and (
			(:rdo_tcls = '00' and a.dcls='1' and a.tcls in ('01','02','03'))
			or (:rdo_tcls = '01' and a.dcls='1' and a.tcls='01' and a.hvseq is null)
			or (:rdo_tcls = '02' and a.dcls='1' and a.tcls='02')
			or (:rdo_tcls = '11' and a.dcls='1' and a.tcls='01' and a.hvseq is not null)
			or (:rdo_tcls = '03' and a.dcls='1' and a.tcls='03')
		)
		and (
			(:rdo_psts = '0' and a.psts=0 and a.ktktcd=h.ktktcd)
			or (:rdo_psts = '-1' and a.psts=-1 and a.ktktcd=h.ktktcd and a.adat>=add_months(h.sdday,-3))	/* 再発行は過去3ヶ月に延長 08/09/27 SE-337 */
		)
		and (:cucd is null or a.cucd = :cucd)
		and (:cuscd is null or a.cuscd = :cuscd)
		and (:chgcd is null or a.chgcd = :chgcd)
		and (:sadat is null or a.adat>=to_date(:sadat,'yyyy/mm/dd'))
		and (:eadat is null or a.adat<=to_date(:eadat,'yyyy/mm/dd'))
		and a.cucd=b.cucd(+)
		and a.cucd=c.cucd(+) and a.cuscd=c.cuscd(+)
		and a.piseq=e.iseq(+)
		and f.cls(+)='9' and b.cudenp1=f.scls1(+)
		and g.cls(+)='9' and b.cudenp2=g.scls1(+)
	group by a.cucd,b.cunm,a.cuscd,c.spnm,a.tcls,
		decode(a.tcls,'01','納品','02','返品','03','値引'),
		decode(a.hvseq,null,0,1),decode(a.hvseq,null,null,'直送'),
		decode(d.cls,0,null,to_char(a.dat2,'yyyy/mm/dd')),
		decode(d.cls,0,null,to_char(a.adat,'yyyy/mm/dd')),
		decode(nvl(e.cls1,'0'),'1',nvl(b.cudenp1,b.cudenp2),b.cudenp2),
		decode(nvl(e.cls1,'0'),'1',nvl(f.nm,g.nm),g.nm),
		decode(d.cls,0,null,a.vseq),
		decode(d.cls,0,null,a.viseq),
		a.psts,
		decode(nvl(e.cls1,'0'),'1',nvl(f.scls7,g.scls7),g.scls7),
		decode(d.cls,0,decode(a.hvseq,null,0,1),null)
) x
order by x.rnum
