无法对表中的数据进行分组

时间:2013-01-25 12:39:43

标签: sql sql-server-2008-r2

Id | MenuName      | vc_Link | SubMenu1 | IsMainMenu | TypeOfMenu
-----------------------------------------------------------------------
1  | Home          |  NULL   |  NULL    |     1      |     0
2  | Projects      |  NULL   |  NULL    |     1      |     0
4  | Pr1           |  NULL   |   2      |     0      |     1
5  | Homesub       |  NULL   |   1      |     0      |     1
6  | Pr1Sub1       |  NULL   |   4      |     0      |     2

以上是我的表结构。

  1. MenuName是菜单和子菜单的名称
  2. SubMenu1是子菜单属于一个特殊节点保存为子菜单的特定菜单
  3. MainMenu有点知道它是菜单还是子菜单。
  4. typeofmenu就是那个
  5. 0 means main menu
    1 means submenu
    2 means submenu's submenu
    

    现在我的问题是我想将其显示如下

       1 Home
          5 HomeSub
       2 Projects
         4 Pr1
             6 Pr1Sub1
    
       Id | MenuName      | vc_Link | SubMenu1 | IsMainMenu | TypeOfMenu
        -----------------------------------------------------------------------
        1  | Home          |  NULL   |  NULL    |     1      |     0
        5  | HomeSub       |  NULL   |  1       |     0      |     1
        2  | Projects      |  NULL   |  NULL    |     1      |     0
        4  | Pr1           |  NULL   |   2      |     0      |     1
        6  | Pr1Sub1       |  NULL   |   4      |     0      |     2
    

    如何分组这样? 只有在像这样分组之后,我才能将此查询的结果作为显示菜单及其子菜单的树结构。

1 个答案:

答案 0 :(得分:2)

这样的事情:

with menu_tree (id, menuname, level, sort_path) as (
   select id, 
          cast(menuname as varchar(max)), 
          1 as level,
          cast(id as varchar(max)) as sort_path
   from menus
   where submenu1 is null
   union all
   select m.id, 
          cast(replicate('_', p.level * 2) + m.menuname as varchar(max)) as menuname, 
          p.level + 1,
          p.sort_path + '_' + cast(m.id as varchar(max))
   from menus m
     join menu_tree p on p.id = m.submenu1
)  
select id, menuname
from menu_tree
order by sort_path;

SQLFiddle:http://sqlfiddle.com/#!3/6c4ba/1