PostgreSQL视图不起作用 - 列不存在

时间:2015-01-22 13:49:29

标签: sql postgresql ms-access views

您好我正在尝试将访问数据库迁移到postgresql中,一切顺利,直到我尝试此视图。我希望它创建一个名为“CalculatedHours”的新列。而作为postgresql的新手,我有点困惑。下面是我一直放入pgAdmin并得到错误的代码......

SELECT "SessionsWithEnrolmentAndGroups"."SessionID", 
        "Assignments"."Staff", 
        "SessionsWithEnrolmentAndGroups"."groups", 
        "SessionsWithEnrolmentAndGroups"."SessionQty",
        "SessionsWithEnrolmentAndGroups"."Hours",
        "SessionsWithEnrolmentAndGroups"."Weeks",
        "Assignments"."Percentage",
        "Assignments"."AdditionalHours", 
        Round((coalesce(("groups"),1)*("SessionQty")*("Hours")*("Weeks")
                   *("Percentage"))) AS CalculatedHours, 
        (CalculatedHours)+coalesce(("AdditionalHours"),0) AS "TotalHours"
FROM "SessionsWithEnrolmentAndGroups" 
INNER JOIN "Assignments" 
ON "SessionsWithEnrolmentAndGroups"."SessionID" = "Assignments"."SessionID";

1 个答案:

答案 0 :(得分:2)

您无法在定义它们的同一select中访问列别名。我会建议一个子查询:

SELECT t.*,
       (CalculatedHours)+coalesce(("AdditionalHours"), 0) AS "TotalHours"
FROM (SELECT eag."SessionID", a, eag."groups", eag."SessionQty",
             eag."Hours", eag."Weeks", a."Percentage", a."AdditionalHours", 
             Round((coalesce(("groups"),1)*("SessionQty")*("Hours")*("Weeks")*("Percentage"))) AS CalculatedHours
      FROM "SessionsWithEnrolmentAndGroups" eag INNER JOIN 
           "Assignments" a
           ON eag."SessionID" = a."SessionID"
     ) t;

使用表别名并删除转义字符(双引号),您的查询也会更具可读性,除非它们真的非常需要。