2017-12-02 113 views
0

我在將SQL翻譯爲LINQ時出現了一些問題,恰恰與Group by和Average混合在一起。我試着用不同的方式解決它,但沒有預期的結果。從SQL到C#LINQ

SQL:

SELECT TOP 3 
    AVG([Grade]) 
    ,[User].FirstName 
    ,[User].Surname 
    ,[Student].StudentID 
    ,[Student].ClassID 

FROM [Szkola].[dbo].[School_Class] 
JOIN [Szkola].[dbo].[Student] 
ON School_Class.ClassID = Student.ClassID 
JOIN [Szkola].[dbo].[School_Grades] 
ON Student.StudentID = School_Grades.StudentID 
JOIN [Szkola].[dbo].[Teacher] 
ON Teacher.TeacherID = School_Grades.TeacherID 
JOIN [Szkola].[dbo].[User] 
ON Student.UserID = [User].UserID 

WHERE [Teacher].[Subject] = 'Mathematics' 
GROUP BY [Student].[StudentID], [Student].[ClassID], [User].[FirstName], 
[User].[Surname] 
ORDER BY AVG([Grade]) DESC 

你能還描述瞭如何準確適用您的解決方案?我閱讀了LINQ和Group by,但我想我會更好地理解這個例子。

非常感謝。

+0

你需要尋找和閱讀一些教程。你有沒有嘗試過任何使用LINQ到目前爲止 –

+0

谷歌搜索SQL平均和GroupBy Linq與2的定義無關,但最好你明白它是什麼關於聚合等..我會開始在那裏.. 1000的sql函數示例/在線說明 – MethodMan

+0

您能否顯示您的努力代碼,這可能是一個很好的起點。我們確實幫助有特定問題的人,但我們不在這裏爲你寫信。 –

回答

2

使用類來模擬數據庫

class Program 
    { 
     static void Main(string[] args) 
     { 
      List<School_Class> classes = new List<School_Class>(); 
      List<Student> students = new List<Student>(); 
      List<School_Grade> grades = new List<School_Grade>(); 
      List<Teacher> teachers = new List<Teacher>(); 
      List<User> users = new List<User>(); 

      var query = (from c in classes 
         join s in students on c.ClassID equals s.ClassID 
         join g in grades on s.StudentID equals g.StudentID 
         join t in teachers on s.StudentID equals t.TeacherID 
         join u in users on s.UserID equals u.UserID 
         select new { c = c, s = s, g = g, t = t, u = u }) 
       .Where(x => x.t.Subject == "Mathematics") 
       .GroupBy(x => new { 
        student = x.s.StudentID, 
        _class = x.c.ClassID, 
        firstname = x.u.FirstName, 
        surname = x.u.SurName }) 
       .OrderByDescending(x => x.FirstOrDefault().g.grades.Average()) 
       .Select(x => new { firstname = x.Key.firstname, 
            surname = x.Key.surname, 
            sid = x.Key.student, 
            cid = x.Key._class, 
            avg = x.FirstOrDefault().g.grades.Average() }) 
       .Take(3).ToList(); 
     } 
    } 
    public class School_Class 
    { 
     public int ClassID { get; set; } 
    } 
    public class Student 
    { 
     public int ClassID { get; set; } 
     public int StudentID { get; set; } 
     public int UserID { get; set; } 
    } 
    public class School_Grade 
    { 
     public int StudentID { get; set; } 
     public int TeacherID { get; set; } 
     public List<int> grades { get; set; } 
    } 
    public class Teacher 
    { 
     public int TeacherID { get; set; } 
     public string Subject { get; set; } 
    } 
    public class User 
    { 
     public string FirstName { get; set; } 
     public string SurName { get; set; } 
     public int UserID { get; set; } 
    }