declare @dte date
select rtrim(actNuMst) as "Account Number", Item, Location, sum(Quantity) as Quantity, sum([Extended Cost]) as [Extended Cost],
sum([0-30]) as [0-30], sum([31-60]) as [31-60], sum([61-90]) as [61-90],
sum([91-120]) as [91-120], sum([121-180]) as [121-180], sum([Over 180]) as [Over 180]
from
(select it.IVIVINDX, rtrim (i.ITEMNMBR) as [Item], i.TRXLOCTN as Location, sum (QTYRECVD-isNull(ii.qtysold,0)) as Quantity,
sum ((QTYRECVD-isNull(ii.qtysold,0)) * i.unitcost) as [Extended Cost],
case when DATEDIFF(day, DATERECD, @dte) between 0 and 30 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [0-30],
case when DATEDIFF(day, DATERECD, @dte) between 31 and 60 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [31-60],
case when DATEDIFF(day, DATERECD, @dte) between 61 and 90 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [61-90],
case when DATEDIFF(day, DATERECD, @dte) between 91 and 120 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [91-120],
case when DATEDIFF(day, DATERECD, @dte) between 121 and 180 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [121-180],
case when DATEDIFF(day, DATERECD, @dte) > 180 then sum (QTYRECVD-isNull(ii.qtysold,0)) else 0 end as [Over 180]
from iv10200 i
join iv00101 it on i.ITEMNMBR = it.ITEMNMBR
left join iv10201 ii on ii.itemNmbr = i.itemNmbr and i.trxLoctn = ii.trxLoctn and srcRctSeqNm = i.rctSeqNm and docDate <= @dte
where i.daterecd <= @dte
group by i.itemnmbr, i.trxloctn, daterecd, it.IVIVINDX) as t1 join gl00105 on t1.IVIVINDX = gl00105.ACTINDX
group by t1.item, t1.location, actNuMst
order by Item