Example of Cast Operator
So long as CAST is used as shown, we could obtain the total marks for each exam in similar fashion, using SUM (Mark) AS TotalMarks. However, this gives NULL, instead of zero, for the courses whose exams nobody sat. That problem can be addressed by using COALESCE, as shown in Example.
Example: Give the total of marks for each exam
WITH C_ER AS (
SELECT CourseId,
CAST (
TABLE (SELECT DISTINCT StudentId, Mark
FROM EXAM_MARK AS EM
WHERE EM.CourseId = C.CourseId )
AS ROW ( StudentId SID, Mark INTEGER) MULTISET)
AS ExamResult
FROM COURSE AS C)
SELECT CourseId, (SELECT SUM (Mark)
FROM TABLE(ER (ExamResult)) AS t) AS n
FROM C_ER
Explanation
- COALESCE((SELECT SUM(Mark) FROM TABLE(ER(ExamResult)) AS t),0) yields the value of the scalar subquery whenever ExamResult is nonempty, otherwise zero. SQL's COALESCE is an n-adic operator that takes a commalist of expressions of the same declared type and yields the result of the first of those expressions, in the order in which they are written, that does not evaluate to NULL. When there is no such operand, it yields NULL anyway, of course.