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 |
pssheba
Yak Posting Veteran
95 Posts |
Posted - 2012-07-24 : 10:16:01
|
Hi everyoneThis is my database:key1 (varchar(2)) key2 (varchar(2)) text_______________ _______________ ____1 NULL abc2 NULL efg3 1 reply(abc)4 2 reply(efg)5 1 reply(abc)6 NULL hij7 5 reply2(abc)I need to display the above lines in the following order:key1 (varchar(2)) key2 (varchar(2)) text_______________ _______________ ____1 NULL abc3 1 reply(abc)5 1 reply(abc)7 5 reply2(abc)2 NULL efg4 2 reply(efg)6 NULL hijThe ratio behind the order stands like:A key2 value: NULL means: first line in a group ("main line").All lines with key2=key1 of "Main line" ("second degree") should be placed beneath the "main line" (reply).Lines with key2=key1 of "second degree" should be placed beneath "second degree" and so on.This is the order posts in a form are placed.Can anyone formulate a query to run upon the db shown above so that the result will look like the secon list?Thanks. |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-07-24 : 11:09:47
|
[code];With CTEAS(SELECT key1,key2,[text],CAST(key1 as varchar(max)) as [path],CAST(1 AS int) AS levelFROM tableWHERE key2 IS NULLUNION ALLSELECT t.key1,t.key2,t.[text],CAST(c.[path] + '\' + CAST(t.key1 AS varchar(max)) AS varchar(max)),c.Level + 1FROM table tINNER JOIN CTE cON c.key1 = t.key2)SELECT key1,key2,[text]FROM CTEORDER BY LEFT([path],CHARINDEX('\',[path] + '\')-1),Level[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
pssheba
Yak Posting Veteran
95 Posts |
Posted - 2012-07-24 : 13:32:29
|
Thanks a lot! |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-07-24 : 14:16:50
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
|
|
|
|
|