-1

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

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,1 门 90,所以我数 3

4

2 回答 2

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 
于 2013-06-08T10:56:35.837 回答
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;
于 2013-06-08T12:00:25.483 回答