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, a.spktcd, to_char(a.ydat, 'yyyy/mm/dd'), to_char(a.climit, 'yyyy/mm/dd'), a.vseq, a.vlin) as rnum,
		a.cucd, m03.cunm, a.cuscd, m032.spnm,
		a.spktcd, m05.ktktnm as spktnm,
		a.gdflg, a.cuslip2,
		to_char(a.ydat, 'yyyy/mm/dd') as ydat,
		to_char(a.climit, 'yyyy/mm/dd') as climit,
		a.cshcd, m036.cshnm,
		comnpack.ClipSltext(b.sltext,2) dcubcd,
		a.vseq, a.vlin dvlin,
		a.ijan,
		m02.jan, m02.gdjnm, m02.gdjstnd, m90.scls5 gdcls9nm,
		m02.gdcnum, m02.gdbnum,
		a.mvpno, a.cst, a.sal,
		calc_amt(a.cucd,a.mvpno,a.cst,a.ktktcd) scst,
		nvl(a.mvpno,0)*nvl(a.sal,0) ssal,
		a.chgcd, m08.chgnm,
		decode(a.jmcat,'1',null,'2','販促・サンプル','3','添付品') jmcatnm,
		decode(a.jmcat,'2','-3','0') jmcatspace
	from afm90 m90, afm08 m08, afm02 m02, afm05 m05,
		 afm036 m036, afm032 m032, afm03 m03,
		 afr31txt b, afr3123 a
	where a.ktktcd = :ktktcd
		and a.iseq=b.iseq(+)
		and a.cucd = m03.cucd(+)
		and a.cucd = m032.cucd(+) and a.cuscd = m032.cuscd(+)
		and a.cucd = m036.cucd(+) and a.cshcd = m036.cshpcd(+)
		and a.spktcd = m05.ktktcd(+)
		and a.ijan = m02.ijan(+)
		and a.chgcd = m08.chgcd(+)
		and m90.cls(+)='6' and m02.gdcls9=m90.scls1(+)
		and (:cucd is null
				or (:cucd is not null and a.cucd = :cucd
					and (:cuscd is null or (a.cuscd = :cuscd))
				)
			)
		and (:sydat is null or a.ydat >= to_date(:sydat, 'yyyy/mm/dd'))
		and (:eydat is null or a.ydat <= to_date(:eydat, 'yyyy/mm/dd'))
		and (:sclimit is null or a.climit >= to_date(:sclimit, 'yyyy/mm/dd'))
		and (:eclimit is null or a.climit <= to_date(:eclimit, 'yyyy/mm/dd'))
		and (:ijan is null or a.ijan = :ijan)
) x
order by x.rnum
