在SQL中查询子查询结果

时间:2016-08-15 20:41:55

标签: sql sql-server

我对SQL比较陌生,我可能会过度思考,但是给出了下表。我想要一份所有注册化学但不是数学的学生的名单。所以我给出了学生1的数据。

    Student_ID  Subject
      1      Chemistry
      2      Mathematics
      2      Chemistry
      3      History

这是我尝试过的事情

SELECT        Student_ID
FROM          Student 
WHERE        (Subject = 'Chemistry') AND (Subject <> 'Mathematics')

也许我需要将某个地方分组,因为这两个标准都存在行并返回。

2 个答案:

答案 0 :(得分:2)

这是使用conditional aggregation的一个选项:

select student_id
from student
group by student_id
having max(case when subject = 'Chemistry' then 1 end) = 1 and
       max(case when subject = 'Mathematics' then 1 else 0 end) != 1

这是使用not exists的另一种选择:

select student_id
from student s
where subject = 'Chemistry' and not exists (
    select 1
    from student s2
    where s.student_id = s2.student_id and st.subject = 'Mathematics'
    )

答案 1 :(得分:0)

您可以在

中使用和不使用
select Student_ID
from Student 
where Subject  = 'Chemistry'
and Student_ID NOT IN  ( select Student_ID from Student where subject ='Mathematics');
相关问题