SQL查询帮助 - 返回表中的行,该行与max(列)的另一个表行相关

时间:2010-06-13 05:58:57

标签: sql sql-server-2008

我有两张桌子:

Table1 = Schools
    Columns: id(PK), state(nvchar(100)), schoolname

Table2 = Grades
    Columns: id(PK), id_schools(FK), Year, Reading, Writing...

我想开发一个查询来查找阅读成绩最高的学校名称。

到目前为止,我有以下内容并需要帮助填补空白:

SELECT Schools.schoolname, Grades.Reading
FROM Schools, Grades
WHERE Schools.id = (* need id_schools for max(Grades.Reading)*)

3 个答案:

答案 0 :(得分:1)

以下是我在不使用子查询的情况下解决此类问题的方法:

SELECT s.*
FROM Schools AS s
JOIN Grades AS g1 ON g1.id_schools = s.id
LEFT OUTER JOIN Grades AS g2 ON g2.id_schools <> s.id
  AND g1.Reading < g2.Reading
WHERE g2.id_schools IS NULL

请注意,如果不止一所学校达到最高阅读分数,您可以获得多行。在这种情况下,您需要决定如何解决关系并将其构建到LEFT OUTER JOIN条件中。


重新评论:左外连接查找同一所学校的成绩较高的行,如果没有找到,则所有g2。*列都将为空。在这种情况下,我们知道没有等级高于g1指向的等级,这意味着g1是该学校的最高等级。它也可以用这种方式编写,逻辑上相同但可能更容易理解:

SELECT s.*
FROM Schools AS s
JOIN Grades AS g1 ON g1.id_schools = s.id
WHERE NOT EXISTS (
    SELECT * FROM Grades g2 
    WHERE g2.id_schools <> s.id AND g2.Reading > g1.Reading)

你说它不起作用。你可以说得更详细点吗?您期望的答案是什么,实际发生了什么,它们有何不同?


修改:根据@potatopeelings的评论建议,将=更改为<>。谢谢!

答案 1 :(得分:1)

SELECT 
     Schools.schoolname, 
     Grades.Reading 
FROM 
     Schools INNER JOIN Grades on Schools.id = Grades.id_schools
WHERE 
     Grades.Reading = (SELECT MAX(Reading) from Grades)

答案 2 :(得分:0)

这应该这样做

select * from Schools as s
where s.id=(
select top(1) id_schools from grades as g
order by g.reading desc)