将CTE与分层数据和累积数据一起使用'值

时间:2015-12-09 16:34:03

标签: sql sql-server-2008 common-table-expression hierarchical-data

我正在尝试使用SQL公用表表达式,使用城市,国家和大洲的样本层次结构,这些表达式已被访问过,并且没有访问过。

表格t_hierarchy如下所示:

The hierarchy table

(注意:对于非城市,visited列故意为NULL,因为我希望这是动态计算的百分比。)

然后我使用以下SQL根据t_hierarchy中的数据创建递归结果集:

WITH myCTE (ID, name, type, parentID, visited, Depth)
 AS
 (
    Select ID, name, type, parentID, visited, 0 as Depth From t_hierarchy where parentID IS NULL
    UNION ALL
    Select t_hierarchy.ID, t_hierarchy.name, t_hierarchy.type, t_hierarchy.parentID, t_hierarchy.visited, Depth + 1 
    From t_hierarchy 
    inner join myCte on t_hierarchy.parentID = myCte.ID
 )

Select ID, name, type, parentID, Depth, cnt.numDirectChildren, visited
FROM myCTE
LEFT JOIN (
          SELECT  theID = parentID, numDirectChildren = COUNT(*)
          FROM    myCTE
          GROUP BY parentID
        ) cnt ON cnt.theID = myCTE.ID

 order by ID

结果如下:

cte result

我现在要做的就是创建一个列,例如: visitedPercentage显示每个'级别的访问过的城市百分比等级(对不同国家和大陆的城市不同)。要解释一下,按照“树”的方式行事:

  • 马德里将是100%,因为它已被访问过(visited = 1)
  • 巴塞罗那将是0%因为已被访问(visited = 0)
  • 西班牙因此有50%,因为它有2个直接子女,一个是100%,另一个是0%
  • 因此,欧洲将是50%,因为西班牙是50%,法国是100%(巴黎已经访问过),德国是0%(柏林没有被访问过)

我希望这是有道理的。我想说"如果它一个城市,根据所有直接孩子的visitedPercentage计算出visitedPercentage这个级别,否则只显示100%或0%。非常感谢任何指导。


更新 我已经设法使用Daniel Gimenez的建议进一步推进,以至于我获得了法国100,西班牙50等等。但是顶级项目(例如欧洲)仍然是0,像这样:

enter image description here

我认为这是因为在查询的递归部分之后正在进行计算,而不是在其中。即这一行:

SELECT... , visitPercent = SUM(CAST visited AS int) / COUNT(*) FROM myCTE GROUP BY parentID

说"查看子对象的visited列,计算值的总和,并将结果显示为visitPercent",当它应该说& #34;查看先前计算中的现有visitPercent值",如果这有意义的话。我不知道从哪里开始! :)

1 个答案:

答案 0 :(得分:1)

我想我已经完成了它,使用了2个CTE。最后,更容易获得每个级别(儿童,孙子女等)的后代总数,并使用它来计算总体百分比。

那很痛苦。有一次打字'CATS'而不是'CAST'让我困惑了大约10分钟。

 no suitable constructor found for Geocoder(RetrieveFeedTask,Locale)
constructor Geocoder.Geocoder(Context) is not applicable
(actual and formal argument lists differ in length)
constructor Geocoder.Geocoder(Context,Locale) is not applicable
(actual argument RetrieveFeedTask cannot be converted to Context by method invocation conversion)

enter image description here

这些帖子很有帮助: