SQL Max和Double Join

时间:2012-05-02 23:45:57

标签: sql

我有以下三个表:

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

subject
-------
subjnumb
subjname
tname

results
-------
stnumb
subjnumb
percent

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

示例 Bob Smith,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

有人可以指出我正确的方向吗?我已经做了好几天了,并没有任何理由。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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中,因为行中的所有其他数据都是相同的,因此选择哪个主题并不重要。

P.S。我没有测试这个查询。可能存在拼写错误,但基本方法是正确的。