0

我有以下三个表:

student
-------
stnumb
stname
gender
grade
born

subject
-------
subjnumb
subjname
tname

results
-------
stnumb
subjnumb
percent

我需要退回highest result and its subject for each student

示例鲍勃·史密斯,IPT,92

我得到的两个最接近的结果是:

SELECT  stname
    ,   subjname
    ,   highestmark
FROM    (
            SELECT      MAX(results.percent) as "highestmark"
                    ,   student.stname
                    ,   subject.subjname
            FROM        student
                    ,   subject
                    ,   results
            WHERE       results.stnumb      = student.stnumb
            AND         results.subjnumb    = subject.subjnumb
            GROUP BY    stname
        ) maxresult

...和...

SELECT      student.stname as Student
        ,   subject.subjname as Subject
        ,   results.percent as Mark
FROM        results 
JOIN        student
ON          results.stnumb = student.stnumb
JOIN        subject
ON          results.subjnumb = subject.subjnumb
ORDER BY    stname

有人可以指出我正确的方向吗?我已经为此工作了好几天,但没有取得任何进展。

4

2 回答 2

0

从 GROUP BY 中缺少subjname来看,这是 MySql。MySql 没有解析功能,所以需要调用 top 1 的旧形式。有派生表保存最大值的版本。此表用于过滤原始表:

SELECT      student.stname as Student
        ,   subject.subjname as Subject
        ,   results.percent as Mark
FROM        results 
JOIN        student
ON          results.stnumb = student.stnumb
JOIN        subject
ON          results.subjnumb = subject.subjnumb
JOIN
(
   SELECT stnumb, MAX(percent) percent
     FROM results
    GROUP BY stnumb
) top1GradePerStudent
  ON results.stnumb = top1GradePerStudent.stnumb
 AND results.percent = top1GradePerStudent.percent
ORDER BY    stname

还有一种not exists方法,只检索百分比不高的学生记录:

SELECT      student.stname as Student
        ,   subject.subjname as Subject
        ,   results.percent as Mark
FROM        results 
JOIN        student
ON          results.stnumb = student.stnumb
JOIN        subject
ON          results.subjnumb = subject.subjnumb
WHERE       NOT EXISTS 
            (
                SELECT null
                  FROM results r2
                 WHERE r2.stnumb = results.stnumb
                   AND r2.percent > results.percent
            )
ORDER BY    stname

两种方式都将返回关系。如果您必须为每个学生创建一条记录,请subjname用 MAX 或 MIN 括起来,因为行中的所有其他数据都将相同,因此您选择哪个科目并不重要。

PS我没有测试这个查询。可能有错字,但基本方法是正确的。

于 2012-05-03T07:53:32.757 回答
0
SELECT pct, subjname, stname 
FROM
(SELECT r.pct, sub.subjname, std.stname,
RANK () OVER (PARTITION BY sub.subjname ORDER BY r.pct) as rk
FROM student std 
INNER JOIN results r ON r.stnumb = std.stnumb 
INNER JOIN subject sub ON sub.subjnumb = r.subjnumb 
GROUP BY sub.subjname, std.stname, r.pct ) a
WHERE rk = 1
于 2012-05-02T23:53:44.067 回答