neo4j cypher - 从两个分组查询中划分结果(第1列/第2列)

时间:2017-12-20 21:08:32

标签: neo4j cypher

假设我有一个图表,将学生与他们的评估联系起来。

(:student)-[:assessed_on]->(:assessment)

评估节点包含告诉我学生如何评估该评估的属性。例如,

math_score: 50

学生节点包含告诉我学生所在的学校的属性。例如,

school_name: 'school_of_rock'

假设我想要回答每所学校50分以上的学生比例。

要获得分子,我可以使用此查询:

MATCH (s:student)-[:assessed_on]->(a:assessment)
WHERE a.math_score>50
RETURN s.school_name as school, count(a) as numerator
ORDER BY school

school              numerator:
------              ---------
school_of_rock       24
school_of_jazz       40
school_of_country    12

要获得分母,我可以做同样的事情,但取出WHERE子句得到总数,返回:

school              denominator:
------              ---------
school_of_rock       48
school_of_jazz       50
school_of_country    48

但我在一个查询中寻找的是以下结果(只是分子/分母):

school              result:
------              ---------
school_of_rock       .5
school_of_jazz       .8
school_of_country    .25

我试过这个:

MATCH (s:student)-[:assessed_with]->(a:assessment)
WHERE a.math_score>50
WITH s.school_name as school, count(a) as numerator
MATCH (s:student)-[:assessed_with]->(a:assessment)
RETURN school, numerator/count(a) as proportion_above_50

但是当我合并查询时分子不正确,所以我显然做错了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

Cypher与自然语言非常相似。所以你说:算我总节点数;然后为我选择必要的;然后需要的数量除以总数。例如:

MATCH (s:student)-[:assessed_on]->(a:assessment)
WITH s.school_name as school, 
     collect(a) as allNodes
WITH school, 
     size(FILTER(a in allNodes WHERE a.math_score > 0.5)) as top,
     size(allNodes)*1.0 as bottom
RETURN school, 
       top/bottom as proportion_above_50
ORDER BY school