select X.StockCode [topLevelPart], X.Qty [topQty],
Coalesce(E.Component,D.Component,C.Component,B.Component,A.Component) [lowerLevelPart],
ISNULL(E.QtyPer,1)*ISNULL(D.QtyPer,1)*ISNULL(C.QtyPer,1)*ISNULL(B.QtyPer,1)*ISNULL(A.QtyPer,1)*X.Qty [Qty]
from (
SELECT InvMovements.StockCode AS StockCode, SUM(InvMovements.TrnQty) AS QTY
FROM InvMovements
INNER JOIN InvMaster ON InvMovements.StockCode = InvMaster.StockCode
WHERE (InvMovements.EntryDate BETWEEN CONVERT(DATETIME, '2010-05-31 00:00:00', 102)
AND CONVERT(DATETIME, '2010-06-27 00:00:00', 102))
AND (InvMovements.TrnType = 'R') AND (InvMaster.ProductClass IN ('PDM', 'PRM', 'TM', 'PM'))
GROUP BY InvMovements.StockCode
) X
inner join BOM A on A.ParentPart = X.StockCode
left join BOM B on B.ParentPart = A.Component
left join BOM C on C.ParentPart = B.Component
left join BOM D on D.ParentPart = C.Component
left join BOM E on E.ParentPart = D.Component
ORDER BY X.StockCode