I would argue that the total quantity available is the package quantity plus the minimum of its components. How can you make 5 new "Package A" items when you only have 2 "Item 1"s available to put in? Regardless, this should give you the totals you asked for. You can modify it if the requirements dictate:declare @Items table ( ItemId int not null, ParentId int null, Name varchar(50) not null, QtyAvailable int not null )insert into @Itemsvalues (1, null, 'Package A', 10), (2, 1, 'Item 1', 2), (3, 1, 'Item 3', 3)-- select * from @Items;with PkgSumsas (select coalesce(ParentId, ItemId) ItemID, sum(QtyAvailable) SumQtyAvailablefrom @Itemsgroup by coalesce(ParentId, ItemId))select i.Name, s.SumQtyAvailablefrom @Items iinner join PkgSums s on s.ItemID = i.ItemId-- This might perform better (?)select i.Name, s.SumQtyAvailablefrom @Items icross apply ( select coalesce(ParentId, ItemId) ItemID, sum(QtyAvailable) SumQtyAvailable from @Items i2 where coalesce(i2.ParentId, i2.ItemId) = i.ItemId group by coalesce(ParentId, ItemId) ) swhere i.ParentId is null
I would rather be the man who bought the Brooklyn Bridge than the one who sold it. -Will Rogers