在论坛中出现的比较难的sql问题:8(递归问题 树形结构分组)

原文: 在论坛中出现的比较难的sql问题:8(递归问题 树形结构分组)

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。 

sql2008 树形结构分组
http://bbs.csdn.net/topics/390634930


ID DeprtID DeprtName 

1   0        1        
2   1        2
3   1        3
4   2        4
5   3        5
6   4        6
7   5        7

分组后效果
ID DeprtID DeprtName 
1   0        1        
2   1        2
4   2        4
6   4        6
3   1        3
5   3        5
7   5        7

 

我的解法:


   
   
  1. --drop table tb
  2. create table tb( ID int, DeprtID int, DeprtName varchar( 10))
  3. insert into tb
  4. select 1, 0, '1'
  5. union all select 2 , 1 , '2'
  6. union all select 3 , 1 , '3'
  7. union all select 4 , 2 , '4'
  8. union all select 5 , 3 , '5'
  9. union all select 6 , 4 , '6'
  10. union all select 7 , 5, '7'
  11. go
  12. ;with t
  13. as
  14. (
  15. select id,DeprtID,DeprtName, 1 as level,
  16. cast( right( '000'+ cast( id as varchar), 3) as varchar( max)) as sort
  17. from tb
  18. where DeprtID = 0
  19. union all
  20. select tb.id,tb.DeprtID,tb.DeprtName, level + 1 ,
  21. cast( sort+ right( '000'+ cast(tb.id as varchar), 3) as varchar( max))
  22. from t
  23. inner join tb
  24. on t.id = tb.DeprtID
  25. )
  26. select id,deprtid,deprtname
  27. from t
  28. order by sort
  29. /*
  30. id deprtid deprtname
  31. 1 0 1
  32. 2 1 2
  33. 4 2 4
  34. 6 4 6
  35. 3 1 3
  36. 5 3 5
  37. 7 5 7
  38. */

这里还有个例子,就是递归查询后,按照树形来排序:


   
   
  1. drop table tb
  2. create table tb
  3. (
  4. id int,
  5. pid int,
  6. name varchar( 20)
  7. )
  8. insert into tb
  9. select 1, null, 'x'
  10. union all select 2, 1, 'a'
  11. union all select 3, 1, 'b'
  12. union all select 4, 2, 'aa'
  13. union all select 5, 3, 'bb'
  14. go
  15. ;with t
  16. as
  17. (
  18. select id,pid, name, 1 as level,
  19. cast( right( '000'+ cast( id as varchar), 3) as varchar( max)) as sort
  20. from tb
  21. where pid is null
  22. union all
  23. select tb.id,tb.pid,tb.name, level + 1 ,
  24. cast( sort+ right( '000'+ cast(tb.id as varchar), 3) as varchar( max))
  25. from t
  26. inner join tb
  27. on t.id = tb.pid
  28. )
  29. select *
  30. from t
  31. order by sort
  32. /*
  33. id pid name level sort
  34. 1 NULL x 1 001
  35. 2 1 a 2 001002
  36. 4 2 aa 3 001002004
  37. 3 1 b 2 001003
  38. 5 3 bb 3 001003005
  39. */


发布了416 篇原创文章 · 获赞 135 · 访问量 94万+

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12019987.html
今日推荐