Author |
Topic |
ZarrinPour
Yak Posting Veteran
66 Posts |
Posted - 2007-04-07 : 15:21:47
|
Hi allI have a Table with Following structure ( a Tree Structure )PK Parent Level Code--- -------- ------- ------1 0 0 1002 1 1 1013 1 1 1024 2 2 1035 3 2 104 6 4 3 105The same as following Tree as you can see 1__ | 2__ | 4__ | 6 | __ 3__ 5I need a query to return the following Result. I think it is possible only through Nested sub-Queries But i don't know how to do thatCould any one help me.?PK Parent Level Value First-Parent' Code 2nd-Parent's Code 3rd-Parent's Code---- -------- ------ ------- --------------------- ---------------------- -----------------------1 0 0 100 NULL NULL NULL2 1 1 101 100 NULL NULL3 1 1 102 100 NULL NULL 4 2 2 103 101 100 NULL 5 3 2 104 102 100 NULL6 4 3 105 103 101 100Any help greatly would be appreciated.Kind Regards. |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-04-07 : 18:45:36
|
[code]declare @table table( PK int, Parent int, Level int, Code int)insert into @tableselect 1, 0, 0, 100 union allselect 2, 1, 1, 101 union allselect 3, 1, 1, 102 union allselect 4, 2, 2, 103 union allselect 5, 3, 2, 104 union allselect 6, 4, 3, 105select t.PK, t.Parent, t.Level, Value = t.Code, [P1 Code] = max(p1.Code), [P2 Code] = max(p2.Code), [P3 Code] = max(p3.Code)from @table tleft join @table p1on t.Parent = p1.PKleft join @table p2on p1.Parent = p2.PKleft join @table p3on p2.Parent = p3.PKgroup by t.PK, t.Parent, t.Level, t.Code[/code] KH |
 |
|
ZarrinPour
Yak Posting Veteran
66 Posts |
Posted - 2007-04-07 : 22:32:41
|
quote: Originally posted by khtan
declare @table table( PK int, Parent int, Level int, Code int)insert into @tableselect 1, 0, 0, 100 union allselect 2, 1, 1, 101 union allselect 3, 1, 1, 102 union allselect 4, 2, 2, 103 union allselect 5, 3, 2, 104 union allselect 6, 4, 3, 105select t.PK, t.Parent, t.Level, Value = t.Code, [P1 Code] = max(p1.Code), [P2 Code] = max(p2.Code), [P3 Code] = max(p3.Code)from @table tleft join @table p1on t.Parent = p1.PKleft join @table p2on p1.Parent = p2.PKleft join @table p3on p2.Parent = p3.PKgroup by t.PK, t.Parent, t.Level, t.Code KH
Hi khtanI lack the word with which to express my thanks. Thanks a million. |
 |
|
|
|
|