oracle sql查询使用group by

时间:2014-10-22 03:21:38

标签: sql oracle

我有以下架构,

学生(名字,姓氏,SID)
已登记(StudentID,CourseID)
课程(CID,CourseName,Department)

我需要弄清楚哪些学生比CSC学习了更多IT课程。 CSCIT位位于Department类别中。我有以下查询,其中列出了所有注册课程的学生以及他们注册了多少CSC门课程。

select studentid,count(department) as cscclasses
from enrolled
left join course
on courseid = cid
and department = 'CSC'
group by studentid;

不太确定如何将此计数与参加IT课程的人数进行比较。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用sumcase

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