How to calculate a column with values dependent on previous calculations using Joins dynamically?

Viewed 222

Current table looks like this:

Each object has a unique name and it's parent name and a hierarchy.

name parent hierarchy value
 A     A        1     100
 B     A        2     0.5
 C     B        3     0.5

My expected result is:

name parent hierarchy value
 A     A        1     100
 B     A        2     50
 C     B        3     25

My query is

    SELECT tb1.[name],
           tb1.[parent],
           tb1.[hierarchy],
           CASE
             WHEN tb1.[hierarchy]=1
               THEN tb1.[value]
             WHEN tb1.[hierarchy]=2
               THEN tb1.[value]*tb2.[value]
           AS [value]
           FROM 
                table tb1
           INNER JOIN 
                table tb2
           ON
                tb1.[parent]= tb2.[name]

This code works only if we have hierarchy 2. How to modify it to work for any number of hierarchy values.

EDIT:

What if it had an id along with which we can identify the data uniquely?

id     name   parent    hierarchy    value
 1        A     A       1             100
 1        B     A       2              50
 1        C     B       3              25
 2        A     A       1              30
 2        D     A       2              0.1
1 Answers

You can try to use cte recursive recursive the hierarchy then self-join in original table.

;with cte as(
 SELECT name,parent,hierarchy,value
 FROM T
 WHERE hierarchy = 1 
 UNION ALL
 SELECT t2.name,t2.parent, t1.hierarchy+1,t1.value * t2.value
 FROM CTE t1 join T t2 on t1.hierarchy+1 = t2.hierarchy
 WHERE t2.name <> t2.parent 
)

SELECT * 
FROM cte

sqlfiddle

Result

name    parent  hierarchy   value
A       A        1          100
B       A        2          50
C       B        3          25
Related