在SQL Server中查找Max Hierarchyid

时间:2016-04-30 13:11:44

标签: sql sql-server tsql sql-server-2012 hierarchy

如何查找max类型列的hierarchyid

例如:

name  | user_hierarchyid
-------------------------
Craig | /
Steve | /1/
John  | /1/1/
Matt  | /1/1/1/
Sam   | /2/
Chris | /2/2/

我尝试使用max(user_hierarchyid),但它会返回/2/2/,但我希望层次结构最多,即/1/1/1/

先谢谢。

3 个答案:

答案 0 :(得分:3)

您可以使用GetLevel()获取关卡,TOP 1 WITH TIES获取" max"(最深)值:

SELECT TOP 1 WITH TIES *
FROM mytable
ORDER BY user_hierarchyid.GetLevel() DESC;

LiveDemo

输出:

╔══════╦══════════════════╗
║ name ║ user_hierarchyid ║
╠══════╬══════════════════╣
║ Matt ║ /1/1/1/          ║
╚══════╩══════════════════╝

或者使用RANK()

SELECT *
FROM (SELECT *, RANK() OVER(ORDER BY user_hierarchyid.GetLevel() DESC) AS rnk
      FROM mytable) AS s
WHERE rnk = 1;

LiveDemo2

答案 1 :(得分:1)

你可以做类似下面的事情

with cte
as
(
select name,user_hier_id,replace(user_hierarchyid,'/','') as rplcd
from table
)
select max(rplcd) from cte

答案 2 :(得分:0)

;WITH cte AS (
SELECT name, CAST(user_hierarchyid as hierarchyid) as user_hierarchyid
FROM (VALUES
('Craig', '/'),
('Steve', '/1/'),
('John', '/1/1/'),
('Matt', '/1/1/1/'),
('Sam', '/2/'),
('Chris', '/2/2/')
) as t(name, user_hierarchyid)
)

SELECT TOP 1
        name,
        CAST(user_hierarchyid as nvarchar(20)) as user_hierarchyid
FROM (
    SELECT  *,
            user_hierarchyid.GetAncestor(CASE WHEN user_hierarchyid.GetLevel() > 0 THEN user_hierarchyid.GetLevel()-1 ELSE user_hierarchyid.GetLevel() END ) as ga,
            user_hierarchyid.GetLevel() as gl
    FROM cte
    ) as t
ORDER BY Rank() OVER (PARTITION BY ga ORDER BY gl,user_hierarchyid ) desc, ga DESC

输出:

name  user_hierarchyid
----- -----------------
Matt  /1/1/1/

(1 row(s) affected)

如果您添加行('Dave', '/1/1/2/'),,则输出将为Dave /1/1/2/

如果您添加行('Tony', '/2/2/1/'),,则输出将为Dave /1/1/2/

如果您添加行('Ann', '/2/2/2/'),,则输出将为Ann /2/2/2/

如果您添加行('Vic', '/1/1/1/1/'),,则输出将为Vic /1/1/1/1/