SQL:对父行下的子行进行排序

时间:2015-03-25 05:41:05

标签: sql sql-server

我的SQL Server数据库中有这个表。

MenuID  MenuText    ParentMenu     MenuOrder        MenuLevel
-------------------------------------------------------------
1   Home                0              1                0
2   Administrator       0              2                0
3   Groups              2              1                1
4   Users               2              2                1
5   Permissions         2              3                1
6   Test Level2         3              1                2
7   Test Level3         6              1                3

我想像这样对这些表行进行排序:

  • HomeAdministrator是MenuLevel 0项。
  • MenuLevel根据指向父ParentMenu的{​​{1}}列,1个项目位于其顶级菜单下。子项将根据其MenuID列进行排序。

我尝试了很多东西,但无法理解如何使用查询来完成。

1 个答案:

答案 0 :(得分:1)

试试这个:

SQL Fiddle

;WITH Cte AS(
    SELECT *,
        DisplayOrder = CAST(ROW_NUMBER() OVER(PARTITION BY ParentMenu ORDER BY MenuOrder) AS VARCHAR(MAX))
    FROM Test
    WHERE
        ParentMenu = 0
    UNION ALL
    SELECT
        t.MenuID,
        t.MenuText,
        t.ParentMenu,
        t.MenuOrder,
        t.MenuLevel,
        DisplayOrder = c.DisplayOrder + CAST(ROW_NUMBER() OVER(PARTITION BY t.ParentMenu ORDER BY t.MenuOrder) AS VARCHAR(MAX))
    FROM Cte c
    INNER JOIN Test t
        ON c.MenuID = t.ParentMenu 
)
SELECT
    MenuID,
    MenuText,
    ParentMenu,
    MenuOrder,
    MenuLevel
FROM cte
ORDER BY DisplayOrder

<强>结果:

| MenuID |      MenuText | ParentMenu | MenuOrder | MenuLevel |
|--------|---------------|------------|-----------|-----------|
|      1 |          Home |          0 |         1 |         0 |
|      2 | Administrator |          0 |         2 |         0 |
|      3 |        Groups |          2 |         1 |         1 |
|      6 |   Test Level2 |          3 |         1 |         2 |
|      7 |   Test Level3 |          6 |         1 |         3 |
|      4 |         Users |          2 |         2 |         1 |
|      5 |   Permissions |          2 |         3 |         1 |