0

做一些练习我不知道如何做这个查询

有这两张桌子

StudentTable ( IDstudent ,....)

考试(IDexam,...,学生,...,结果)

在哪里

  • 学生考试参考 IDstudent in student
  • resutl 有一个布尔值

例子

 StudentTable
 IDstudent
 S0001
 S0002
 S0003


 EXAM
 IDexam     student    result
  1          S0001      true
  2          S0002      true
  3          S0002      true
  4          S0003      false

查询必须显示考试中真实人数最多的学生的ID和人数

在示例 S0002 2 的情况下

我试过了

  SELECT 
      student, count(1)
  FROM
       Exam  E join StudentTable  S on E.student=S.id_student
  WHERE result='true'
  GROUP by student 

我所拥有的是

    S0001    1
    S0002    2

但我不知道如何取最大值

  • 我能怎么做?

这是架构http://sqlfiddle.com/#!2/895ea/8的链接

4

3 回答 3

4

尝试这个:

  SELECT 
    student, count(1)
  FROM
       Exam  E join StudentTable  S on E.student=S.id_student
  WHERE result='true'
  GROUP by student 
  ORDER by 2 DESC
  LIMIT 0,1

MySQL中的LIMIT(N,N)子句等价于T-SQL中的TOP(N)

于 2013-05-27T09:32:00.127 回答
3

我喜欢这个查询的一件事是它支持具有最多true答案的重复学生。

SELECT  a.*
FROM    StudentTable a
        INNER JOIN
        (
            SELECT  Student
            FROM    Exam
            WHERE   result = 'true'
            GROUP   BY Student
            HAVING  COUNT(*) =
                    (
                        SELECT  COUNT(*) count
                        FROM    Exam
                        WHERE   result = 'true'
                        GROUP   BY Student
                        ORDER   BY count DESC
                        LIMIT   1
                    )
        ) b ON a.IDStudent = b.Student
于 2013-05-27T09:39:36.090 回答
2

尝试这个:

SELECT 
  student, count(result) AS number
FROM
   Exam  E join StudentTable  S on E.student=S.id_student
WHERE 
   result='true'
GROUP BY 
   student 
HAVING 
   number = (SELECT COUNT(result) FROM exam WHERE result='true' GROUP BY student ORDER BY 1 DESC LIMIT 1)

链接到SQL 小提琴

于 2013-05-27T09:32:09.547 回答