Check this:
DECLARE @commodity TABLE(id INT IDENTITY(1,1), parentID INT, [name] VARCHAR(30))
INSERT INTO @commodity(parentID, [name])
VALUES(null, 'foods'),
(1, 'fruits'),
(2, 'apple'),
(2, 'orange'),
(2, 'melon'),
(1, 'sea foods'),
(6, 'salmon'),
(6, 'shrimp')
DECLARE @saleDetail TABLE(commodityID INT, [count] INT, price INT)
INSERT INTO @saleDetail (commodityID, [count], price)
VALUES(3, 1, 100),
(4, 1, 150),
(5, 1, 200),
(7, 1, 110),
(8, 1, 180),
(4, 1, 160)
;WITH tree AS
(
SELECT c.ID, c.parentID, c.[name], sd.[count] AS countOfItems, sd.price
FROM @saleDetail AS sd INNER JOIN @commodity AS c ON sd.commodityID = c.id
UNION ALL
SELECT c.ID, c.parentID, c.[name], t.countOfItems, t.price
FROM @commodity AS c INNER JOIN tree AS t ON c.id = t.parentID
)
SELECT t.[name], SUM(t.countOfItems * t.price) AS total
FROM tree AS T
GROUP BY t.[name]
Result:
name total
apple 100
foods 900
fruits 610
melon 200
orange 310
salmon 110
sea foods 290
shrimp 180