MYSQL - MAX()和GROUP BY()没有按预期结果

时间:2018-05-25 12:22:53

标签: mysql sql

运行sql后

SELECT 
        m.stdClassID,
        m.Percentage,
        sc.ClassID,
        sc.Form,
        sc.FormName,
        sc.Year,
        sc.stdName
FROM stdremark  m
INNER JOIN (
    SELECT
        sc.ClassID,
        c.Form,
        c.FormName,
        sc.stdClassID,
        c.Year,
        CONCAT(s.StdFname,' ',s.StdLname) as stdName
    FROM tblstdclass sc 
    INNER JOIN tblclass c
        ON sc.ClassID=c.ClassID
    INNER JOIN tblstudents s
        ON sc.StdID = s.StdID
    WHERE c.Year=2018
) sc ON m.stdClassID=sc.stdClassID
WHERE m.Term=3`

我想出了这个结果 我想获得按表格列分组的每个学生的最大百分比

result of sql

当我尝试获得Max()和分组时() 来自sql:

SELECT 
        m.stdClassID,
        MAX(m.Percentage),
        sc.ClassID,
        sc.Form,
        sc.FormName,
        sc.Year,
        sc.stdName
FROM stdremark  m
INNER JOIN (
    SELECT
        sc.ClassID,
        c.Form,
        c.FormName,
        sc.stdClassID,
        c.Year,
        CONCAT(s.StdFname,' ',s.StdLname) as stdName
    FROM tblstdclass sc 
    INNER JOIN tblclass c
        ON sc.ClassID=c.ClassID
    INNER JOIN tblstudents s
        ON sc.StdID = s.StdID
    WHERE c.Year=2018
) sc ON m.stdClassID=sc.stdClassID
WHERE m.Term=3
GROUP BY sc.Form`

but what am actually getting as result is

预期结果应该是

17     71     28     upper     Science     2018     Jerry Maguire

1 个答案:

答案 0 :(得分:2)

可能是MySQL允许部分分组的问题。尝试将GROUP BY表达式扩展到所有列上的组,m.Percentage除外。

...
GROUP BY m.stdClassID,
         sc.ClassID,
         sc.Form,
         sc.FormName,
         sc.Year,
         sc.stdName

无论如何,其他DBMS会强迫你这样做。