postgres=# WITH RECURSIVE cte(id, pid, rate) AS (SELECT id, pid, rate FROM t a UNION ALL SELECT cte.id, b.pid, b.rate * cte.rate / 100 FROM t b INNER JOIN cte ON b.id = cte.pid ) SELECT id, rate FROM cte WHERE pid = 0 ORDER BY id; id | rate ------+------ 1000 | 8 1001 | 9 1002 | 40 2000 | 24 2001 | 4 2002 | 12 3000 | 7 3001 | 2 (8 rows)