简体   繁体   中英

oracle sql query using group by

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.

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM