Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
samir.first
Starting Member
34 Posts |
Posted - 2014-05-21 : 02:03:31
|
I have Table with 3 columnscol1 col2 col3 A samir LA samir ZA Ali EC Jon BC Beter T..... etc I need To convert This Table To TreeID Col1 ParentID1 A NULL2 Samir 13 L 24 Z 25 Ali 16 E 57 C Null8 Jon 79 Beter 7 Samir |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2014-05-21 : 03:25:56
|
[code]declare @tbl table( col1 varchar(10), col2 varchar(10), col3 varchar(10))insert into @tbl (col1, col2, col3)select 'A', 'samir', 'L' union allselect 'A', 'samir', 'Z' union allselect 'A', 'Ali', 'E' union allselect 'C', 'Jon', 'B' union allselect 'C', 'Beter', 'T'; with cte as( select ID = row_number() over (order by coalesce(parent, col), case when parent is null then 1 else 2 end), col, parent from ( select col = col1, parent = NULL from @tbl group by col1 union all select col = col2, parent = col1 from @tbl group by col2, col1 union all select col = col3, parent = col2 from @tbl group by col3, col2 ) c)select c1.ID, c1.col, ParentID = c2.IDfrom cte c1 left join cte c2 on c1.parent = c2.col[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|
|
|
|
|
|