select x.*,
	ceil(rnum / :lcnt) as pgno,
	0 chkval,
	max(rnum) over() as maxnum
from (
	select
		ROW_NUMBER() OVER (ORDER BY z.brand) as rnum,
		z.*,
		case
			when nvl(z.amt01,0)=0 then
				case when nvl(z.amt02, 0) = 0 then 0 else 999.99 end
			else abs(round(z.amt02/nvl(z.amt01,0)*100,2))
		end rt02, /*返品率*/
		decode(nvl(z.amt,0), 0, 999.99, abs(round(nvl(z.ar,0)/nvl(z.amt,0)*100,2))) as rtar, /*粗利率*/
		decode(nvl(z.tamt02,0), 0, 0, decode(nvl(z.tamt01,0), 0, 0, abs(round(nvl(z.tamt02,0)/nvl(z.tamt01,0)*100,2)))) as trt02, /*合計返品率*/
		decode(nvl(z.tar,0), 0, 0, decode(nvl(z.tamt,0), 0, 0, round(nvl(z.tar,0)/nvl(z.tamt,0)*100,2))) as trtar /*合計粗利率*/
	from (
		select
			b.brand,
			c.nm as brandnm,
			sum(decode(a.tcls,'01',a.amt)) as amt01,
			nvl(sum(decode(a.tcls,'02',a.amt)),0) as amt02,
			sum(a.tpno) as tpno,
			sum(a.amt) as amt,
			sum(a.amt-calc_amt(null,a.tpno,a.fcst,2,a.ktktcd,z.scutaxc)) as ar,
			sum(nvl(sum(decode(a.tcls,'01',a.amt)),0)) over() as tamt01,
			sum(nvl(sum(decode(a.tcls,'02',a.amt)),0)) over() as tamt02,
			sum(nvl(sum(a.tpno),0)) over() as ttpno,
			sum(sum(a.amt)) over() as tamt,
			sum(nvl(sum(a.amt-calc_amt(null,a.tpno,a.fcst,2,a.ktktcd,z.scutaxc)),0)) over() as tar
		from axm99 z,afm90 c,afm02 b,aur32 a
		where a.ktktcd=:ktktcd
			and a.dcls='1'
			and a.adat>=to_date(:adats, 'yyyy/mm/dd')
			and a.adat<=to_date(:adate, 'yyyy/mm/dd')
			and (:cucd is null or (:cucd is not null and a.cucd = :cucd and (:cuscd is null or a.cuscd = :cuscd)))
			and a.ijan=b.ijan(+)
			and c.cls(+)='7' and b.brand=c.scls1(+)
			and a.ktktcd=z.ktktcd(+)
			group by b.brand,c.nm
	) z
) x
order by x.rnum
