[英]Query Subquery Results in SQL
我對SQL比較陌生,可能會想得不明白,但是給出了下表:我想要列出所有已注冊化學而不是數學的學生的清單,因此給定數據,我將擁有學生1。
Student_ID Subject
1 Chemistry
2 Mathematics
2 Chemistry
3 History
這是我嘗試過的
SELECT Student_ID
FROM Student
WHERE (Subject = 'Chemistry') AND (Subject <> 'Mathematics')
也許我需要將其分組,因為這兩個條件都存在行和返回值。
這是使用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'
)
您可以使用where而不是in
select Student_ID
from Student
where Subject = 'Chemistry'
and Student_ID NOT IN ( select Student_ID from Student where subject ='Mathematics');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.