Wednesday, May 16, 2012

Can I use Nhibernate QueryOver to group and count by a collection's count of an entity?

There are two classes in my project like below:



public class Teacher
{
public virtual long Id {get;set;}
public virtual IList<Student> Students {get;set;}
}


public class Student
{
public virtual long Id {get;set;}
public virtual string Name {get;set;}
}


I need a query which get Students' count of each Teacher and group by with the count result. Also with the frequency of each count(eh... count of count number). I don't know how to do this using queryover. It's like if given data like this:



teacher1.Students = [student1,student2,student3] //teacher1's student count is 3
teacher2.Students = [student4]
teacher3.Students = [student5,student6,student7]
teacher4.Students = [student8]
teacher5.Students = [] //empty


I need query result like this:



[
[0,1], //1 teacher has 0 students
[1,2],
[3,2] //2 teachers have 3 students
]


Updated: the sql is like this:



select tc.tCount, count(tc.TRID)
from (select tr.Id as TRID, count(std.Id) as tCount
from Teacher tr
JOIN Student std on std.TeacherId = tr.Id
GROUP BY tr.Id ) as tc GROUP BY tc.tCount




No comments:

Post a Comment