SQL Server:如何从同一个表中检索顶级组ID

时间:2016-02-24 10:59:10

标签: sql-server-2008-r2

我有SQL Server 2008 R2。

我的源表如下所示:

EmpID      Name   GroupID
-------------------------
1-KFX       xxx    7-ZQMN
7-ZQMN      yyy    null
AXM-4       zzz    1-KFX
7-ZQOP      JJJ    QRS-0
QRS-0       kkk    null

依旧......

我需要遍历表格以获取每个Top GroupID的{​​{1}}(层次结构中的顶部),直到EmpID为空,并填充GroupID EmpID }是null

我正在尝试编写一个查询来获得如下所示的结果,感谢任何帮助。

GroupID

2 个答案:

答案 0 :(得分:2)

通过使用recursive CTE查找根节点来解决此层次结构问题。

CREATE TABLE #tt(EmpID VARCHAR(128) NOT NULL PRIMARY KEY,Name VARCHAR(128),GroupID VARCHAR(128));
INSERT INTO #tt(EmpID,Name,GroupID)VALUES
    ('1-KFX','xxx','7-ZQMN'),
    ('7-ZQMN','yyy',null),
    ('AXM-4','zzz','1-KFX'),
    ('7-ZQOP','JJJ','QRS-0'),
    ('QRS-0','kkk',null);

;WITH cte_tr AS (
    SELECT EmpId, GroupID, depth=0
    FROM #tt
    UNION ALL -- what follows is the recursion in the CTE to find the parent, keeping track of depth
    SELECT cte_tr.EmpID, GroupId=t.GroupID, depth=cte_tr.depth+1
    FROM cte_tr 
         INNER JOIN #tt AS t ON 
             t.EmpID=cte_tr.GroupID
    WHERE t.GroupID IS NOT NULL
),
cte_depth AS ( -- select the maximum depth for a starting node
    SELECT EmpID, max_depth=MAX(depth)
    FROM cte_tr
    GROUP BY EmpID
)
SELECT cte_depth.EmpID, TopGroupId=ISNULL(cte_tr.GroupID,cte_tr.EmpID)
FROM cte_depth 
     INNER JOIN cte_tr ON -- select the nodes at the maximum depth
         cte_tr.EmpID=cte_depth.EmpID AND 
         cte_tr.depth=cte_depth.max_depth
ORDER BY cte_tr.EmpID;

DROP TABLE #tt;

结果:

+--------+------------+
| EmpID  | TopGroupId |
+--------+------------+
| 1-KFX  | 7-ZQMN     |
| 7-ZQMN | 7-ZQMN     |
| 7-ZQOP | QRS-0      |
| AXM-4  | 7-ZQMN     |
| QRS-0  | QRS-0      |
+--------+------------+

答案 1 :(得分:0)

试试这个......

select
    empid,
    name
    isnull(max(GroupID),empid) 'TopGroupId'
    from tablename
    group by 
    empid,name
    order by empid