Neo4j查询需求:在用户帖子反应统计中新增总反应数列
解决方案
可以通过窗口函数实现需求,既保留原有统计字段,又新增每个帖子发布者的总反应数。以下是两种可行的修改方案:
方案一:分步聚合(逻辑更清晰)
MATCH (z:User)-[re:REACTED]->(p:Post)<-[:POSTED]-(x:User) WHERE exists(re.type) WITH x.name as postOwner, re.type as rectionType, count(re) as noOfReactions, collect(re.type) as reactionList WITH postOwner, rectionType, noOfReactions, reactionList, sum(noOfReactions) OVER (PARTITION BY postOwner) as totalReactions RETURN postOwner, rectionType, noOfReactions, reactionList, totalReactions
方案二:直接在返回语句中使用窗口函数(写法更简洁)
MATCH (z:User)-[re:REACTED]->(p:Post)<-[:POSTED]-(x:User) WHERE exists(re.type) RETURN x.name as postOwner, re.type as rectionType, count(re) as noOfReactions, collect(re.type) as reactionList, count(re) OVER (PARTITION BY x.name) as totalReactions
核心说明
- 窗口函数
OVER (PARTITION BY x.name)会忽略当前按postOwner和rectionType的分组,单独统计每个用户名下所有反应的总数,完美匹配需求。 - 给
collect(re.type)命名为reactionList是为了字段名更规范,你也可以保留原写法不命名。
内容的提问来源于stack exchange,提问作者Surya Teja Patkari
相关产品推荐
相关产品推荐

