在RETURN语句中使用计算的Neo4J查询

时间:2017-08-10 15:18:38

标签: neo4j cypher

我有一个简单的模型:

(teacher)-[:HAD]->(contract)-[:WITH]-(school)

一位教师可以与同一所学校或其他学校签订一份以上的合同。现在,合同上的财产是{leadership: 'Senior Leader'},我正在试图询问所有高级领导,以了解他们签订了多少所学校。

//FIND ALL HEADS AND NUMBER OF SCHOOLS THEY WENT TO
MATCH (t:Teacher)
WHERE (t)-[:HAD]->(:Contract {leadership: 'Head'})
MATCH (t)-[:HAD]->(:Contract)-[:WITH]->(s:School)
RETURN t,count(distinct(s)) as nr_of_schools
ORDER BY nr_of_schools DESC

我想在计算中使用nr_of_schools

toFloat(no_of_schools) / count(distinct(t))*100
ORDER BY toFloat(no_of_schools) / count(distinct(t))*100 DESC
本质上我发现70%的校长到1所学校,20%的校长到2所学校,其余到3所学校。我以为我可以使用no_of_schools作为参数,但我不认为这是可能的。

1 个答案:

答案 0 :(得分:1)

您可以使用WITH进行中间计算:

//FIND ALL HEADS AND NUMBER OF SCHOOLS THEY WENT TO
MATCH (t:Teacher)
WHERE (t)-[:HAD]->(:Contract {leadership: 'Head'})
MATCH (t)-[:HAD]->(:Contract)-[:WITH]->(s:School)
WITH t,count(distinct(s)) as no_of_schools
RETURN toFloat(no_of_schools) / count(distinct(t))*100 AS ratio
ORDER BY ratio DESC

如果您希望返回t以及稍微重写查询所需的比率 - 您无法在变量上返回变量和聚合 - RETURN t,count(t)是不可能的。< / p>

MATCH (t:Teacher)
WITH count(t) as tCount // don't need distinct here, but wouldn't hurt
MATCH (t:Teacher)
WHERE (t)-[:HAD]->(:Contract {leadership: 'Head'})
MATCH (t)-[:HAD]->(:Contract)-[:WITH]->(s:School)
WITH t,tCount,count(distinct(s)) as no_of_schools
RETURN toFloat(no_of_schools) / tCount*100 AS ratio
ORDER BY ratio DESC