如何获得学生ID,其中学生获得A级而不是C级

时间:2017-03-31 22:35:33

标签: sql

表 .......

student_id   Grade
1              A
1              B
1              D
2              B
2              C
2              A

期望的输出 .............

student_id
1

我试过了 ............

select student_id from student where grade='A' and not grade='c';

但我的输出错误

2 个答案:

答案 0 :(得分:2)

一种简单的方法是聚合和having子句:

select student_id
from student
group by student_id
having sum(case when grade = 'A' then 1 else 0 end) > 0 and
       sum(case when grade = 'C' then 1 else 0 end) = 0;

答案 1 :(得分:1)

A的成绩选择,student_id再次将成绩加入成绩并C,并排除匹配。

select distinct
 a.student_id
from grades as a
  left join grades as c
  on c.student_id = a.student_id
  and c.Grade = 'C'
where a.Grade = 'A'
and c.student_id is null -- exclude students with C's

这是demo