同时使用group by和order

时间:2013-09-16 12:53:32

标签: sql

我有4张桌子

Class(ID,Name)
Month(ID,Name)
Student(ID,Name)
Examination(ID,Student,Class,Month,TotalMarks,ObtainedMarks)

student,class,month已作为Examination表格中的参考。

我想从Examinationorder by ObtanedMarks and Group by Class

中选择记录

我使用了以下SQL查询

SELECT     Months.Name, Class.Name AS Classname, Students.Name AS Studentname, Examination.*
FROM         Class INNER JOIN
                      Examination ON Class.ID = Examination.Class INNER JOIN
                      Months ON Examination.Month = Months.ID INNER JOIN
                      Students ON Examination.Student = Students.ID
                      order by Obtained desc Group by Class.Name 

但查询对我不起作用。

1 个答案:

答案 0 :(得分:2)

看起来错误的方式,Group ByOrder By之前。您需要在Group By中添加所有列,或者在字段中使用聚合函数SumMax等不在Group By条款中。

查看更新的查询...

SELECT  Months.Name ,
        Class.Name AS Classname ,
        Students.Name AS Studentname ,
        E.Student ,
        E.Class ,
        E.[Month] ,
        E.TotalMarks ,
        E.ObtainedMarks
FROM    Class
        INNER JOIN Examination E ON Class.ID = E.Class
        INNER JOIN Months ON E.[Month] = Months.ID
        INNER JOIN Students ON E.Student = Students.ID
GROUP BY Class.Name ,
        Months.Name ,
        Students.Name ,
        E.Student ,
        E.Class ,
        E.[Month] ,
        E.TotalMarks ,
        E.ObtainedMarks
ORDER BY Obtained DESC