在单个Cypher查询中返回两个聚合?

时间:2012-09-04 18:04:03

标签: neo4j cypher

我一直在与Cypher讨论两个值的SUM并发现差异。我有这两个查询,它们查找已发送的总数和节点的总接收数:

START addr = node(5)
MATCH addr <- [:owns] - owner - [to:transfers] -> receiver
RETURN SUM(to.value) AS Total_Sent

START addr = node(5)
MATCH addr <- [:owns] - owner <- [from:transfers] - sender
RETURN SUM(from.value) AS Total_Received

基本上我的问题是 - 如何组合这两个单独的查询,以便我可以区分Total_Sent和Total_Received?我尝试了多个起点:

START sendAddr = node(5), receivedAddr = node(5)
MATCH sendAddr <- [:owns] - sendOwner - [to:transfers] -> receiver, receivedAddr <- [:owns] - receiveOwner <- [from:transfers] - sender
RETURN SUM(to.value) AS Total_Sent, SUM(from.value) AS Total_Received, SUM(to.value) - SUM(from.value) AS Balance

但Total_Received为空!对我来说,这看起来像一个非常简单的用例 - 我到底做错了什么?

1 个答案:

答案 0 :(得分:4)

您不能将两个查询组合在一起,就像那样粉碎它们。 :)

要解决此问题,我建议您使用WITH将查询分为两部分,如:

START addr = node(5)
MATCH addr <- [:owns] - owner - [to:transfers] -> receiver
WITH addr, SUM(to.value) AS Total_Sent

MATCH addr <- [:owns] - owner <- [from:transfers] - sender
WITH SUM(from.value) AS Total_Received, Total_Sent

RETURN Total_Received, Total_Sent, Total_Received - Total_Sent as Total_Balance

HTH,

安德烈斯