Mysql:从不同的id中选择最大计数

时间:2013-06-08 10:53:21

标签: mysql count group-by max

我有两个表学生和考试看起来像

student(studentid,lastname,firstname,class)

exam(studentid,course,mark,result)

我需要找到最好的学生,每个班级有90分,100分。

这就是我需要的

class     studentid  best
K11       K1101       3    
K12       K1203       2
K13       K1305       2

这是我的第一个代码

Select st.class, st.studentid, count(st.mark) as best
From exam e inner join student st on e.studentid = st.studentid
Where e.mark = 90 or e.mark = 100
Group by e.studentid

返回

class     studentid  best
K11       K1101       3
K12       K1201       1
K12       K1203       2
K13       K1305       2

所以我尝试了另一个代码

Select st.class, st.studentid, count(st.mark) as best
From exam e inner join student st on e.studentid = st.studentid
Where e.mark = 90 or e.mark = 100
Group by st.class
Having count(e.mark) = 
       (Select max(count)
        From (Select count(ex.mark) count
              From exam ex
              Where ex.mark = 90 or ex.mark = 100
              Group by ex.studentid) a) 

仍然得到错误答案

class     studentid  best
K11       K1101       3
K12       K1201       3

更新数据

抱歉不明白的问题。我需要找到每个班级的学生都有很多精确分数为90或100的课程。这是我的数据

studentid    course   mark result
K1101        DB       100  Pass
K1101        CD       90   Pass
K1101        DIP      95   Pass
K1101        OT       100  Pass
K1102        DB       97   Pass
K1102        CD       65   Pass
K1102        DIP      70   Pass
K1102        OT       44   Fail
K1201        DB       85   Pass
K1201        CD       90   Pass
K1201        DIP      76   Pass
K1201        OT       65   Pass
K1202        DB       69   Pass
K1202        CD       32   Fail
K1202        DIP      57   Pass
K1202        OT       96   Pass
K1203        DB       90   Pass
K1203        CD       87   Pass
K1203        DIP      90   Pass
K1203        OT       91   Pass
K1301        DB       75   Pass
K1301        CD       79   Pass
K1301        DIP      78   Pass
K1301        OT       63   Pass
K1305        DB       90   Pass
K1305        CD       93   Pass
K1305        DIP      100  Pass
K1305        OT       80   Pass

在这种情况下,在K11班,学生K1101有2门课程100,一门90,所以我算3

2 个答案:

答案 0 :(得分:0)

试试这个

Select   st.class, st.studentid, count(mark) as best
From exam e inner join student st on e.studentid = st.studentid
Where e.mark between 90 and 100
and e.mark in (select max(mark) from exam group by studentid)
Group by st.class 

答案 1 :(得分:0)

您的结果似乎与问题的措辞不一致。你说:“我需要找到最好的学生,每班90分,100分。”但是,该表仅显示每个班级一名学生,甚至认为计数栏有三个。

如果您需要了解每个班级的内容,那么您应该按班级分组。如果你需要向所有学生展示。将这些放在一起:

Select st.class, group_concat(st.studentid), count(st.mark) as best
From exam e inner join
     student st
     on e.studentid = st.studentid
Where e.mark in (90, 100)
Group by st.class;

如果你想计算一个学生的课程数量:

Select st.studentid, group_concat(st.class), count(st.mark) as best
From exam e inner join
     student st
     on e.studentid = st.studentid
Where e.mark in (90, 100)
Group by st.studentid;