Domanda

I'm very new to SQL, I am trying to get the sum of the credit hours a student has taken based on if they were elective hours or core hours. I'm checking the COURSE_TAKEN table which gives which courses they've taken and then comparing the courses taken to see if they are core courses or elective courses and then trying to get two separate sums. I end up getting 0 for both sums though, don't know why.

Select nvl(sum(C.Credit_Hours),0) As CoreCreditHours, 
       nvl(sum(C1.Credit_Hours),0) As ElectiveCreditHours
FROM COURSE C 
JOIN COURSE_TAKEN ON 
    C.CRN = COURSE_TAKEN.CRN
JOIN COURSE C1 ON
    C1.CRN = COURSE_TAKEN.CRN
WHERE C.CRN IN(
    SELECT MINOR_CORE_REQUIREMENTS.CRN
    FROM MINOR_CORE_REQUIREMENTS
    WHERE MINOR_CORE_REQUIREMENTS.Minor_Name = 'Computer Science')
AND C1.CRN IN (
    SELECT MINOR_ELECTIVE_REQUIREMENTS.CRN
    FROM MINOR_ELECTIVE_REQUIREMENTS
    WHERE MINOR_ELECTIVE_REQUIREMENTS.Minor_Name = 'Computer Science')
AND COURSE_TAKEN.H_Number = 1; 
È stato utile?

Soluzione

You need to use outer joins in case the student doesn't have courses in one of the categories:

Select nvl(sum(C.Credit_Hours),0) As CoreCreditHours, 
       nvl(sum(C1.Credit_Hours),0) As ElectiveCreditHours
FROM COURSE_TAKEN
LEFT JOIN COURSE C ON 
    C.CRN = COURSE_TAKEN.CRN AND C.CRN IN(
        SELECT MINOR_CORE_REQUIREMENTS.CRN
        FROM MINOR_CORE_REQUIREMENTS
        WHERE MINOR_CORE_REQUIREMENTS.Minor_Name = 'Computer Science')
LEFT JOIN COURSE C1 ON
    C1.CRN = COURSE_TAKEN.CRN AND C1.CRN IN (
        SELECT MINOR_ELECTIVE_REQUIREMENTS.CRN
        FROM MINOR_ELECTIVE_REQUIREMENTS
        WHERE MINOR_ELECTIVE_REQUIREMENTS.Minor_Name = 'Computer Science')
WHERE COURSE_TAKEN.H_Number = 1; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top