来自sql server的父子结果?

时间:2013-05-17 09:33:16

标签: sql sql-server

我有一张表category,如下所示:

id      title      ParentID
1       C1          0
2       C2          0
3       C3          0
4       C4          2
5       C5          1
6       C6          3
7       C7          4

我希望结果为

id  title      ParentID   Level
1   C1          0         0
5   C5          1         1
2   C2          0         0
4   C4          2         1
7   C7          4         2  
3   C3          0         0
6   C6          3         1

我怎样才能得到这个结果?

订单说明:我希望结果包含其父项下面的项目。

2 个答案:

答案 0 :(得分:4)

此答案假定您使用的是SQL Server 2008或更高版本。

使用递归CTE并按顺序构建您在hierarchy id中使用的id的字符串。

with C as
(
  select id,
         title,
         parentid,
         '/'+cast(id as varchar(max))+'/' as sort,
         1 as lvl
  from YourTable
  where parentid = 0
  union all
  select T.id,
         T.title,
         T.parentid,
         C.sort + cast(T.id as varchar(10)) + '/',
         C.lvl + 1
  from YourTable as T
    inner join C
      on T.parentid = C.id
)
select id,
       title,
       parentid,
       lvl,
       sort
from C
order by cast(sort as hierarchyid)

SQL Fiddle

答案 1 :(得分:3)

使用递归CTE,它基本上构建从根项到物品的物化路径:

; WITH cte 
  (id, title, parentID, path) 
AS
( SELECT 
      id, 
      title, 
      parentID,
      CAST(RIGHT(REPLICATE('0',9)  
                 + CAST(id AS VARCHAR(10))
                ,10) AS VARCHAR(MAX)) 
  FROM 
      category
  WHERE
      parentID = 0
UNION ALL
  SELECT 
      a.id,
      a.title,
      a.parentID,
      CAST(b.path 
           + RIGHT(REPLICATE('0',9) 
                   + CAST(a.id AS VARCHAR(10))
                  ,10) AS VARCHAR(MAX))
  FROM 
      category AS a
    JOIN 
      cte AS b 
        ON b.id = a.parentID
)
SELECT id, title, parentID
FROM cte
ORDER BY path ;

SQL-Fiddle

进行测试