我有以下架构,
学生(名字,姓氏,SID)
的已登记(StudentID,CourseID)
课程(CID,CourseName,Department)
我需要弄清楚哪些学生比CSC
学习了更多IT
课程。 CSC
和IT
位位于Department
类别中。我有以下查询,其中列出了所有注册课程的学生以及他们注册了多少CSC
门课程。
select studentid,count(department) as cscclasses
from enrolled
left join course
on courseid = cid
and department = 'CSC'
group by studentid;
不太确定如何将此计数与参加IT课程的人数进行比较。
答案 0 :(得分:1)
您可以尝试使用sum
和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
答案 1 :(得分:1)
在CTE中,计算每个学生的CSC和IT课程计数
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