Sql层次结构ID按级别排序

时间:2012-01-17 17:47:04

标签: sql sql-server-2008 hierarchy hierarchyid

是否可以按层次结构ID对层次结构中的sql数据进行排序,然后按字母顺序对每个级别排序进行排序?

所以说我们有一个Employees Table,它列出了基于Employees ID的组织层次结构

你有Bob(5)有Phil(17)和Charlie(28)向他报告,而Josie(6)有Tyler(15)和Mike(56)向她报告。

如果按HierarchyID排序,它将如下所示:

鲍勃(/ 5 /)
--Phil(/ 5/17 /)
- 查理(/ 5/28 /)
乔西(/ 6 /)
- 泰勒(/ 6/15 /)
- 迈克(/ 6/56 /)

但让它看起来像

可能更有意义

鲍勃
--Charlie
--Phil
乔西
--Mike
--Tyler

如果没有它太复杂,这可能吗?

3 个答案:

答案 0 :(得分:2)

- 这会有用吗?这取自Sorting tree with other column in SQL Server 2008

DECLARE @table TABLE (id INT NOT NULL PRIMARY KEY, name NVARCHAR(4000) NOT NULL, path HIERARCHYID)

INSERT
INTO    @table
VALUES  
        (1, 'People', '/'),
        (2, 'Girls', '/1/'),
        (3, 'Boys', '/2/'),
        (4, 'Zoey', '/1/1/'),
        (5, 'Kate', '/1/2/'),
        (6, 'Monica', '/1/3/'),
        (7, 'Mark', '/2/1/'),
        (8, 'David', '/2/2/')

;WITH   q AS
        (
        SELECT  *, HIERARCHYID::Parse('/') AS newpath
        FROM    @table
        WHERE   path = HIERARCHYID::GetRoot()
        UNION ALL
        SELECT  t.*, HIERARCHYID::Parse(q.newpath.ToString() + CAST(ROW_NUMBER() OVER (ORDER BY t.name) AS NVARCHAR(MAX)) + '/')
        FROM    q
        JOIN    @table t
        ON      t.path.IsDescendantOf(q.path) = 1
                AND t.path.GetLevel() = q.path.GetLevel() + 1
        )
SELECT  replicate(convert(nvarchar, '-'), q.path.GetLevel()) + q.name /*+ '(' + q.newpath.ToString() + ')'*/
FROM    q
ORDER BY
        newpath

答案 1 :(得分:2)

这是我找到的解决方案

declare @oldId hierarchyid, @newId hierarchyid, @parent hierarchyid

select @oldId = id_node, @parent = id_node.GetAncestor(1)
from gbs.T_Hierarchy_Activities ha
where ID = @ID_Object

select @newId = @oldId.GetReparentedValue(@oldId, ID_Node) from (
    select row_number() over(order by id_node) rn, id_node
    from gbs.T_Hierarchy_Activities ha
        cross join (select * from common.FX_Permissions() where ID_Feature = 10) p
    where ID_Node.IsDescendantOf(@oldId.GetAncestor(1)) = 1
        and ID_Level = @oldId.GetLevel()
        and ha.ID_Office = p.ID_Office
) a
where rn = @NewPosition

update gbs.T_Hierarchy_Activities
set ID_Node = case when ID_Node = @oldId then @newId else @oldId end
where ID_Node in (@oldId, @newId)

答案 2 :(得分:0)

除非我误解了某些内容,否则您只需在ORDER BY子句中添加辅助排序字段即可。例如:

SELECT * FROM Employees ORDER BY HierarchyID, Name