COALESCE(SUM(...),0)COALESCE(COUNT(...),0)在我的代码中不起作用

时间:2019-02-01 15:23:36

标签: sql postgresql

我正在尝试使用COALESCE而不是NULL来获得0,但似乎不起作用。这是我的代码。您可以在下图看到当前结果是什么。 result

CREATE VIEW "PathToGraduation" (student, "totalCredits", "mandatoryLeft", "mathCredits", "researchCredits", "seminarCourses")
AS  SELECT idnr, "A".credits, "B"."mandatoryLeft", "C"."mathCredits", "D"."researchCredits", "E"."seminarCourses"
     FROM   "Students"
          LEFT OUTER JOIN (
               SELECT student, COALESCE(SUM(credits),0) AS credits
               FROM   "PassedCourses"
               GROUP BY student) AS "A"
               ON idnr = "A".student
          LEFT OUTER JOIN (
               SELECT UM.student, COALESCE(COUNT(UM.student),0) AS "mandatoryLeft"
               FROM  "Students" S, "UnreadMandatory" UM
               WHERE S.idnr = UM.student
               GROUP BY UM.student) AS "B"
               ON idnr = "B".student
          LEFT OUTER JOIN (
               SELECT PC.student, COALESCE(SUM(PC.credits),0) AS "mathCredits"
               FROM "PassedCourses" PC, "Classified" CL
               WHERE CL.course = PC.course AND CL.classification = 'math'
               GROUP BY "student") AS "C"
               ON idnr = "C".student
          LEFT OUTER JOIN (
               SELECT PC.student, COALESCE(SUM(PC.credits),0) AS "researchCredits"
               FROM "PassedCourses" PC, "Classified" CL
               WHERE CL.course = PC.course AND CL.classification = 'research'
               GROUP BY "student") AS "D"
               ON idnr = "D".student
          LEFT OUTER JOIN (
               SELECT PC.student, COALESCE(COUNT(PC.course),0) AS "seminarCourses"
               FROM "PassedCourses" PC, "Classified" CL
               WHERE CL.course = PC.course AND CL.classification = 'seminar'
               GROUP BY "student") AS "E"
               ON idnr = "E".student;

1 个答案:

答案 0 :(得分:1)

COALESCE表达式将在查询产生的每一行中产生一个非空值(如果有一个可用值)。但是,如果查询根本不产生任何行,则不会评估COALESCE表达式。

SELECT已经有机会将“无行”变成LEFT JOIN时,最好将它们向上移到外部NULL

SELECT idnr, COALESCE("A".credits,0), COALESCE("B"."mandatoryLeft",0), 
             COALESCE("C"."mathCredits",0), COALESCE("D"."researchCredits",0), 
             COALESCE("E"."seminarCourses",0)
FROM   "Students"
      LEFT OUTER JOIN (
         SELECT student, SUM(credits) AS credits
         ...