neo4j有没有把返回值行转列的方法?
发布于 3 年前 作者 zhd0105 608 次浏览 来自 问答

我现在有这样一个查询语句

MATCH (a:Article)–(p:Institute) WITH p, collect(a) as c CALL { WITH c UNWIND c as n RETURN sum(n.score) as score } WITH p, c, score ORDER BY score DESC LIMIT 100 CALL { WITH c UNWIND c as n RETURN count(n) as subScore, n.type as type } return p.name as name, score, subScore, type

简而言之就是查询文章总分前100的机构,然后获得每种的文章type的文章数 其中文章的类型是固定几类,假设种类现在是"type1",“type2”,“type3”

问题来了: 上述查询语句返回的结果结构是 name score subScore type 公司1 1100 20 type1 公司1 1100 110 type2 公司1 1100 510 type3 公司2 550 0 type1 公司2 550 20 type2 公司2 550 50 type3 ……

而我希望返回结果是 name score type1 type2 type3 公司1 1100 20 110 510 公司2 550 0 20 50 ……

自然,我可以把查询语句改成

MATCH (a:Article)–(p:Institute) WITH p, collect(a) as c CALL { WITH c UNWIND c as n RETURN sum(n.score) as score } WITH p, c, score ORDER BY score DESC LIMIT 100 CALL { WITH c UNWIND [n in c WHERE n.type = “type1”] as n RETURN count(n) as type1 } CALL { WITH c UNWIND [n in c WHERE n.type = “type2”] as n RETURN count(n) as type2 } CALL { WITH c UNWIND [n in c WHERE n.type = “type3”] as n RETURN count(n) as type3 } return p.name as name, score, type1, type2, type3

但是问题又来了,这个type将来可能有变化,所以又不能把查询语句写死。 请问有什么好办法吗

1 回复

我自己弄出来了……

MATCH (a:Article)–(p:Institute) WITH p, collect(a) as c CALL { WITH c UNWIND c as n RETURN sum(n.score) as score } WITH p, c, score ORDER BY score DESC LIMIT 100 CALL { WITH c UNWIND c as n WITH count(n) as value, n.type as type RETURN apoc.map.fromPairs(collect([type, value])) AS prop } return apoc.map.merge(prop, {name: p.name, score: score}) AS output

回到顶部