Wellbl2
Wellbl2

Reputation: 3

SQL: CTE using IIF

The problem I am trying to solve:

Write a CTE with a SELECT statement that returns one row for each student that has courses with these columns:

Write a SELECT statement that uses this CTE to return these columns for each student:

What I am running:

WITH UnitsSummary AS (
SELECT Students.StudentID,SUM(CourseUnits) AS TotalUnits
FROM Students JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID
JOIN Courses ON StudentCourses.CourseID = Courses.CourseID
GROUP BY Students.StudentID,CourseUnits
)

SELECT StudentID, TotalUnits, IIF( SUM (TotalUnits) >9,'FUlltime','Parttime'),FullTimeCost + (TotalUnits * PerUnitCost) AS Tuition
FROM UnitsSummary CROSS JOIN Tuition

My error message:

Msg 8120, Level 16, State 1, Line 8 Column 'UnitsSummary.StudentID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Upvotes: 0

Views: 436

Answers (1)

zealous
zealous

Reputation: 7503

You do not need to sum(TotalUnits) again. Whenever you use aggregated function you have to do group by non-aggregated field. Try the following

SELECT 
    StudentID, 
    TotalUnits, 
    IIF(TotalUnits > 9,'FUlltime','Parttime'),
    FullTimeCost + (TotalUnits * PerUnitCost) AS Tuition
FROM UnitsSummary 
CROSS JOIN Tuition

Upvotes: 1

Related Questions