2

我有一个如下表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

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

订单说明:我想要项目低于其父项目的结果。

4

2 回答 2

4

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

使用递归 CTE 并构建您按顺序使用的 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小提琴

于 2013-05-17T10:55:01.767 回答
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进行测试

于 2013-05-17T11:29:38.600 回答