Neo4j合并了两个查询

时间:2017-05-25 20:05:59

标签: neo4j cypher

我想将这两个查询合并在一起:

查询1(和结果):

MATCH (Professor)-[:liest]->(Vorlesung)-[:wird_gehoert]->(Studenten)
RETURN Professor.Name, COUNT(Studenten.MatrNr) 

Professor.Name  COUNT(Studenten.MatrNr)
Augustinus  2
Russel  2
Sokrates    4
Kant    4
Popper  1

查询2(和结果):

MATCH (Professor)-[:liest]->(Vorlesung)
RETURN Professor.Name, sum(Vorlesung.SWS)

Name    COUNT(Studenten.MatrNr)
Augustinus  2
Russel  2
Kant    4
Sokrates    4
Popper  1

我试过了:

MATCH (Professor)-[:liest]->(Vorlesung)-[:wird_gehoert]->(Studenten)
RETURN Name, COUNT(Studenten.MatrNr), sum(Vorlesungen.SWS)

但我收到了错误的答案:

Professor.Name  COUNT(Studenten.MatrNr) sum(Vorlesung.SWS)
Augustinus  2   4
Russel  2   5
Sokrates    4   14
Kant    4   16
Popper  1   2

如何将两个查询合并在一起?

1 个答案:

答案 0 :(得分:0)

如果只返回匹配结果:

MATCH (Professor)-[:liest]->(Vorlesung)-[:wird_gehoert]->(Studenten)
RETURN Professor, Vorlesung, Studenten

您会看到每一行都是教授,讲座和该讲座中的学生的组合。这意味着,同一位教授的多个讲座的学生将多次出现在该教授身上(每次单独讲课一次),这可能会使学生失去学分,而且你也会出现同样的讲座。有学生参加那个讲座,这会甩掉你的sum()计算。

为避免计算重复条目,您需要稍微处理一下查询。这是我最好的猜测,但有助于了解Studenten.MatrNrVorlesung.SWS代表什么。如果MatrNr是学生的唯一号码,那么最好统计不同的学生节点:

MATCH (Professor)-[:liest]->(Vorlesung)-[:wird_gehoert]->(Studenten)
// need to aggregate Vorlesung so we get an accurate count of distinct students
WITH Professor, collect(DISTINCT Vorlesung) as Vorlesungen, count(DISTINCT Studenten) as StudentenCount
// need to unwind back to rows so we can sum across distinct Vorlesung
UNWIND Vorlesungen as Vorlesung
RETURN Professor, sum(Vorlesung.SWS) as swsSum, StudentenCount