递归和数据透视查询不起作用

时间:2016-10-25 06:29:28

标签: sql-server

我有一个表以父子关系存储地理层次结构

Geo Table的示例数据是

 ChildName      ChildCode   ParentName     ParentCode ChildLevelName
 A9             DG1-100     NULL            NULL         Geography_Display_Big_Area
 United States  DG2-200     A9              DG1-100      Geography_Display_Area
 United States  DG3-300     United States   DG2-200      Geography_Display_Region
 United States  LC          United States   DG3-300      Geography_Display_Sub_Region
 United States  JW          United States   LC           Geography_Display_SalesLocation

我希望结果是

Display_Big_Area    Display_Area    Display_Region  Display_Sub_Region  Display_SalesLocation
 A9                 United States   United States   United States       United States

我尝试使用PIVOT

SELECT ChildName,
[Geography_Display_Area], [Geography_Display_Big_Area],
 [Geography_Display_Region], [Geography_Display_SalesLocation],
 [Geography_Display_Sub_Region]
 from
(
 SELECT childname,parentCode, parentname,childlevelname
 from Table
) as st
 pivot
(
 max(ParentName)
FOR childlevelname in ([Geography_Display_Area],
   [Geography_Display_Big_Area], [Geography_Display_Region],
   [Geography_Display_SalesLocation], [Geography_Display_Sub_Region])
 ) as pivottable

Result

  childname   Geography_Display_Area    Geography_Display_Big_Area  Geography_Display_Region    Geography_Display_SalesLocation Geography_Display_Sub_Region
   United States          A9                    NULL                        United States                     United States                     United States

但层次结构似乎得到了重新安排

有人可以帮我解决问题。

1 个答案:

答案 0 :(得分:1)

您可以使用子节点和父节点的左连接(self)。如果长度始终相同,则可以使用此查询

    SELECT 
   tt.ChildName Geography_Display_SalesLocation,
   tt2.ChildName [Geography_Display_Sub_Region],
   tt3.ChildName [Geography_Display_Region],
   tt4.ChildName [Geography_Display_Area],
   tt5.ChildName [Geography_Display_Big_Area]
 FROM   
   TestTable tt
     LEFT JOIN TestTable tt2
       ON tt.ParentCode = tt2.ChildCode
     LEFT JOIN TestTable tt3
       ON tt2.ParentCode = tt3.ChildCode
     LEFT JOIN TestTable tt4
       ON tt3.ParentCode = tt4.ChildCode
     LEFT JOIN TestTable tt5
       ON tt4.ParentCode = tt5.ChildCode
 WHERE  
   tt.ChildLevelName = 'Geography_Display_SalesLocation'

您没有使用PIVOT的

组字段