select x.*,
    ceil(rnum / :lcnt) as pgno,
    max(rnum) over() as maxnum
from (
	select z.*,
	    ROW_NUMBER() over (order by z.vseq,z.vlin) as rnum
	from (
		select 
			a.ktktcd,
			a.spktcd,
			a.cls,
			a.cls1,
			a.iseq,
			a.idat,
			a.tono vseq,
			a.togyo vlin,
			a.vend,
			a.jan,
			a.ijan,
			a.cst,
			a.cno,
			a.chgcd,
			a.dat,
			decode(cls1,'8',a.pno,'9',a.pno9,null) wpno,
			a.pno,
			a.pno1,
			a.pno9,
			a.pno2,
			a.pno3,
			a.obat,
			c.gdjnm,
			c.gdjstnd,
			c.gdcls9,
			g.scls5 gdcls9nm
		from afm90 g, afm05 d, afm02 c, afr3161 a 
		 where a.cls='61'
		   and a.cls1 = :cls1
		   and a.ktktcd = :ktktcd
		   and a.spktcd = :spktcd
		   and a.tono = :vseq
		   and ((:cls = '1') or (:cls = '2' and ((a.cls1='8' and a.pno<>a.pno1) or (a.cls1='9' and a.pno9<>a.pno1))))
		   and a.ijan = c.ijan(+)
           and g.cls(+)='6' and c.gdcls9=g.scls1(+)
		   and a.spktcd=d.ktktcd
		   and d.rep=0
		   and a.flg=1
		 order by tono,togyo
	) z
) x