If my tables are setup like this:
Apply: studentID, cName
Student: studentID, sName
How can I list studentID and sName from Student where there are entries in Apply that have:
Apply.studentID = Student.studentID AND Apply.cName = "College1"
AND
Apply.studentID = Student.studentID AND Apply.cName = "College2"
Ultimately, what I am trying to do is list the students that have applied to both colleges with cNames "College1" and "College2"..
By doing two subqueries, one to get the studentIDs that applied to College1 and another for College2 you can ensure that the students returned from Student have studentIDs that exist in both of the subquery result sets.
SELECT sName
FROM Student
WHERE studentID IN (
SELECT DISTINCT studentID FROM Apply WHERE cName='College1'
)
AND studentID IN (
SELECT DISTINCT studentID FROM Apply WHERE cName='College2'
)
You can check if it EXISTS with both criteria:
select * from Student s
where exists
(select * from Apply a where a.StudentId = s.StudentId and a.cName = 'College1') and
exists
(select * from Apply a where a.StudentId = s.StudentId and a.cName = 'College2');
You can use CTE
to avoid duplicated codes.
with
cte
as
(
select
studentID
from
[Apply]
where
cName in('College1', 'College2')
)
select
s.sName
from
cte
inner join
Student s
on
cte.studentID = s.studentID;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.