如何在Neo4j的Cypher查询语言中使用类似SQL的GROUP BY?

时间:2012-12-05 20:34:10

标签: neo4j cypher

我想查找公司中所有用户的数量以及男性和女性的数量。我的疑问是:

 start n=node:company(name:"comp")
 match n<-[:Members_In]-x, n<-[:Members_In]-y  
 where x.Sex='Male' and y.Sex='Female' 
 return n.name as companyName, count(distinct x) as NumOfMale,
 count(distinct y) as NumOfFemale" );

我的查询是正确的,但我知道我不应该在match子句中使用n<-[:Members_In]-y

我如何获得男性人数,女性人数和总用户数?

3 个答案:

答案 0 :(得分:3)

彼得在这里创建了一个交叉产品:

我认为这对您的用例更有效

start n=node:node_auto_index(name='comp')
match n<-[:Members_In]-x
with  n.name as companyName, collect(x) as employees
return length(filter(x in employees : x.Sex='Male')) as NumOfMale,
length(filter(x in employees : x.Sex='Female')) as NumOfFemale,
length(employees) as Total

请参阅http://console.neo4j.org/r/msamaa

答案 1 :(得分:2)

尝试

start n=node:node_auto_index(name='comp')
match n<-[:Members_In]-x, n<-[:Members_In]-y  
where x.Sex='Male' and y.Sex='Female' 
with 
n.name as companyName, 
count(distinct x) as NumOfMale,
count(distinct y) as NumOfFemale
return NumOfMale, NumOfFemale, NumOfMale + NumOfFemale as Total

有关示例,请参阅http://tinyurl.com/cjpxrax

答案 2 :(得分:0)

实际上有一种更简单的方法来实现这个结果

START n=node:node_auto_index(name='comp') 
MATCH n<-[:Members_In]-x 
RETURN count(x.name), x.Sex

看看http://architects.dzone.com/articles/neo4jcypher-sql-style-group 应该是非常有帮助的,以为我的答案有点迟了......