基于SQL Server中的父节点对子节点和孙节点分组的分层数据

时间:2015-02-05 07:43:05

标签: sql sql-server-2012

我拥有如下所示的分层数据:

hierarchyID  hierarchylevel    Name
0xB6               1           President
0xB6B0             2           Manager
0xB6B580           3           Project Head
0xB6B5AC           4           QA LEAD
0xB6B5AD60         5           SSE
0xB6B5B4           4           SE

以上数据的分层树结构如下所示:

            President   
                |
             Manager    
                | 
           Project head 
                |
       QA LEAD       SE     
          |
         SSE        

我正在尝试使用SQL SERVER 2012

显示如下所示的数据
Level1      Level2    Level3         Level4           Data
President                                             Manager
President   Manager                                   Project head
President   Manager   Project head                    QALEAD
President   Manager   Project head                    SE
President   Manager   Project head   QALEAD           SSE

您能否帮我解决一下如何为此编写SQL查询。

1 个答案:

答案 0 :(得分:0)

喜欢这个吗?

DECLARE @Example TABLE ([hierarchyID] hierarchyid, [hierarchylevel] int, [Name] varchar(20))

INSERT INTO @Example ([hierarchyID], hierarchylevel, Name)
SELECT 0xB6, 1, 'President' UNION ALL
SELECT 0xB6B0, 2, 'Manager' UNION ALL
SELECT 0xB6B580,3, 'Project head' UNION ALL 
SELECT 0xB6B5AC,4, 'QA LEAD' UNION ALL
SELECT 0xB6B5AD60, 5, 'SSE' UNION ALL
SELECT 0xB6B5B4, 4, 'SE'

SELECT 
  MAX(CASE WHEN e2.hierarchylevel=1 AND e2.hierarchylevel<e1.hierarchylevel THEN e2.Name ELSE NULL END) as level1,
  MAX(CASE WHEN e2.hierarchylevel=2 AND e2.hierarchylevel<e1.hierarchylevel THEN e2.Name ELSE NULL END) as level2, 
  MAX(CASE WHEN e2.hierarchylevel=3 AND e2.hierarchylevel<e1.hierarchylevel THEN e2.Name ELSE NULL END) as level3, 
  MAX(CASE WHEN e2.hierarchylevel=4 AND e2.hierarchylevel<e1.hierarchylevel THEN e2.Name ELSE NULL END) as level4, 
  e1.Name as Data
FROM @Example e1
INNER JOIN @Example e2 ON e1.hierarchyID.IsDescendantOf(e2.hierarchyID)=1
WHERE e1.hierarchylevel>1 
GROUP BY e1.Name, e1.hierarchylevel
ORDER by e1.hierarchylevel