我有一张表category,如下所示:
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
我怎么能得到这个结果?
订单说明:我想要结果低于其父项目的项目。
该答案假定您使用的是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小提琴