cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Need help to frame a query

Hi
I have a node class with student_name and class_name as attributes. How can I frame a query to find how many students belong to each class?
Thank you.

7 REPLIES 7

not a lot to go upon here. but lets say

create (n:Student {id:1, name:'Emil'});
create (n:Student {id:2, name:'Jim'});
create (n:Student {id:3, name:'Philip'});

create (n:Class {id:1, name:'Math'});
create (n:Class {id:2, name:'History'});

match (n:Student {name:'Jim'}), (n2:Class {name:'Math'}) create (n)-[:ATTENDS]->(n2);
match (n:Student {name:'Jim'}), (n2:Class {name:'History'}) create (n)-[:ATTENDS]->(n2);
match (n:Student {name:'Emil'}), (n2:Class {name:'History'}) create (n)-[:ATTENDS]->(n2);
match (n:Student {name:'Philip'}), (n2:Class {name:'History'}) create (n)-[:ATTENDS]->(n2);

then

match (c:Class) return c.name, size  (   (c)<-[:ATTENDS]-() );

will report

Math   1
History 3

Thank you so much for your help. But in my case both student_name and student_class are attributes of one node and so, there is no relationship (as you mentioned in your solution) for my node. Each student has (id, name, class) and I want to find how many students are enrolled for class1,class2, class3 etc. Hope you understand my question.

what queries have you tried

match (n:Class) return n.class_name,count(n.student_name);

Thank you so much. Got the result. 🙂

Try this:

MATCH (a:Student) 
//to get student count.........
with distinct a.class as Class, count(distinct a.id) as Count
RETURN Class, Count order by Count desc 

//use this to get student ids as an array
with distinct a.class as Class, collect(a.id) as ids
RETURN Class, ids, size(ids) as Count

This also worked. Great! Thank you so much 🙂

You might want to rethink your schema....

What you describing kind of defeats to purpose of a Graph DB.