在 SPARQL 中显示树的所有路径

Show all paths of a tree in SPARQL

考虑一棵树:

prefix : <http://example.org/random#>

    :A a :Black .
    :B a :Black .
    :C a :Red .
    :D a :Black .
    :E a :Red .
    :F a :Black .
    :G a :Black .
    :H a :Red .
    :A :hasChild :B .
    :A :hasChild :C .
    :B :hasChild :D .
    :C :hasChild :E .
    :C :hasChild :F .
    :F :hasChild :G .
    :F :hasChild :H .

每个底部节点代表一条路径。

从根节点 :A 到每个底部节点的路径时,如何计算 "class changes" 的数量?

如果父节点和子节点具有不同的 classes 红色/黑色,则会发生 class 变化。结果应如下所示:

?bottom  ?num
:D       0
:E       1
:G       2
:H       3

我尝试了不同的方法,例如:

prefix : <http://example.org/random>
SELECT ?bottom (COUNT(distinct IF(?type1 != ?type2,1,0)) AS ?num)
WHERE {

       :A :hasChild* ?child, ?mid, ?bottom .

        ?child a ?type1 .
        ?mid a ?type2 .


       FILTER NOT EXISTS {?bottom :hasChild ?x}


} group by ?bottom

这给了我:

bottom  num

E       "2"
D       "2"
G       "2"
H       "2" 
prefix : <http://example.org/random#> 

select (?end as ?bottom) (sum(?change) as ?num) 

where { 

?begin :hasChild* ?midI . 
FILTER NOT EXISTS { [] :hasChild ?begin } 
?midI :hasChild ?midJ . 
?midI a ?iType . 
?midJ a ?jType . 
BIND(IF(?iType != ?jType, 1, 0) as ?change) 
?midJ :hasChild* ?end . 
FILTER NOT EXISTS { ?end :hasChild [] } 

} group by ?begin ?end order by ?num

@Uninformeduser 回答