2015-02-24 140 views
1

我在使用LINQ完成这个任务时遇到了一些麻烦。没有太多的经验。
我有以下信息: 学校,考试,教师,学生Linq group by sub grouping

我需要的学校数量和教师对每个测试的次数的计数,但我只需要计算实例,其中老师,测试,有超过10名学生。

这里是SQL:

select 
    test, 
    count(distinct school) school_count, 
    count(distinct teacher) teacher_count 
from 
    (select 
    test, 
    teacher, 
    school 
    from list 
    group by 
    test, 
    school, 
    teacher 
    having 
    count(teacher) > 10) a 
group by a.test 

我的结构非常简单。一个类(不是实际的代码)

class tests 
{ 
public string teacher; 
public string test; 
public string school; 
public string studentid; 
} 

然后我有一个测试列表,我正在做查询。
}

+0

这里是一个教程,可能有助于解释如何使用“分组依据”子句 [SQL Tutorial Group By](http://beginner-sql-tutorial.com/sql-group-by-clause.htm) – MethodMan 2015-02-24 16:32:50

回答

0

Linq中的wherehaving之间没有区别。你可以做到以下几点:

void Tests(IEnumerable<tests> tests) 
{ 
    var result = 
     from t in tests.Select(t => new {Teacher = t.teacher, Test = t.test, School = t.school}).Distinct() 
     group t by t.Test 
     into g 
     where g.Select(t => t.Teacher).Distinct().Count() > 10 
     select new 
     { 
      Test = g.Key, 
      TeacherCount = g.Select(t => t.Teacher).Distinct().Count(), 
      SchoolCount = g.Select(t => t.School).Distinct().Count() 
     }; 

} 

旁注:你的数据库结构可能需要normalization,你的命名约定不recommended

+0

对不起,我没有添加我正在使用的结构。我已经在上面添加了它。与你的假设不太一样。 – user568551 2015-02-24 16:51:58

+0

@ user568551答案已更新 – Bas 2015-02-24 17:07:38

+0

我试过了,但没有奏效。是的,结构应该更加标准化,但它实际上是我读的一个csv文件,而不是数据库。我在下面写了一篇文章,讲述了一些正在工作但不太优雅的东西 – user568551 2015-02-24 19:27:49

0
var initial_group = from st in this       group st by new { st.TestName, st.School, st.Teacher } 
          into testGroups 
          where testGroups.Count() > 10 
          select new 
          { 
           Test = testGroups.Key.TestName, 
           School = testGroups.Key.School, 
           Teacher = testGroups.Key.Teacher, 
           Items = testGroups 
          }; 

    var results = from grp in initial_group 
        group grp by grp.Test 
         into testGroups 

         select new 
          { 
           Test = testGroups.Key, 
           NumSchools = testGroups.Select(a => a.School).Distinct().Count(), 
           NumTeachers = testGroups.Select(a => a.Teacher).Distinct().Count() 
          }; 

这是有效的,但它看起来不太优雅。能很好地结合这两个查询。