Search code examples
neo4jnosqlneo4j-apoc

Neo4j compare sums from different queries and display result


Is there a way that i compare results from different queries? Could the following queries be written in a single query together with the return for the wanted result?

Query1: Returns countries and SUM from all points given by countries that are not part of their region.

MATCH (c:Country)
with c
MATCH (c)-[vFrom:vote_from]->(vP:vote_points)-[vFor:vote_for]->(c2:Country)
with c,c2,vP
where not c.region=c2.region
return c2.name,sum(toInteger(vP.points))

Example return from Query1:

"Monaco"    11
"Montenegro"    34
"France"    359
"Cyprus"    600
"Romania"   837

Query2: Returns countries and SUM from all points given by countries that are part of their region.

MATCH (c:Country)
with c
MATCH (c)-[vFrom:vote_from]->(vP:vote_points)-[vFor:vote_for]->(c2:Country)
with c,c2,vP
where  c.region=c2.region
return c2.name,c.name,sum(toInteger(vP.points))

Example return from Query2:

"Monaco"    35
"Montenegro"    66
"France"    157
"Cyprus"    102
"Romania"   255

Wanted result:

"Monaco"    35
"Montenegro"    66

Solution

  • Assuming that you are looking for cases where in-region point totals exceed out-of-region totals, this query may work for you:

    MATCH (c:Country)-[:vote_from]->(vP:vote_points)-[:vote_for]->(c2:Country)
    WITH c2,
      REDUCE(s={in: 0, out: 0}, x IN COLLECT({reg: c.region, pts: toInteger(vP.points)}) |
        CASE WHEN x.reg=c2.region
          THEN {in: s.in + x.pts, out: s.out}
          ELSE {in: s.in, out: s.out + x.pts}
        END) AS res
    WHERE res.in > res.out
    RETURN c2.name AS name, res.in AS points