Reputation: 38
I have the following schema,
Student(FirstName,LastName,SID)
Enrolled(StudentID,CourseID)
Course(CID, CourseName,Department)
I need to figure out which students took more CSC
classes than IT
. The CSC
and IT
bit are found in the Department
category. I have the following query which lists all the students who enrolled in courses and how many CSC
courses they enrolled in.
select studentid,count(department) as cscclasses
from enrolled
left join course
on courseid = cid
and department = 'CSC'
group by studentid;
Not quite sure how to compare this count with those enrolled in IT courses.
Upvotes: 1
Views: 72
Reputation: 2449
you may try to use sum
and case
select studentid
from(
select studentid,
SUM(CASE WHEN department='CSC'
THEN 1
ELSE 0
END) as cscclasses,
SUM(CASE WHEN department='IT'
THEN 1
ELSE 0
END) as itclasses
from enrolled
left join course
on courseid = cid
and department = 'CSC' OR department = 'IT'
group by studentid
)
where cscclasses > itclasses
Upvotes: 1
Reputation: 13425
In CTE , each student's CSC and IT course count is calculated
With CTE
As
(
select studentid,
SUM(case when
department ='CSC'
then 1 else 0
end) as CSCCount ,
SUM(case when
department ='IT'
then 1 else 0
end) as ITCount ,
from enrolled
left join course
on courseid = cid
And Sid =studentid
group by studentid
)
Select E.* FROM
JOIN CTE
On CTE.studentid = E.sid
Where CTE.CSCCount > CTE.ITCount
Upvotes: 1