横向查询语法

时间:2016-09-06 11:49:42

标签: postgresql

我正试图在Postgres 9.5.3查询中进行工作。

select  b_ci."IdOwner",
ci."MinimumPlaces",
ci."MaximumPlaces",
(select count(*) from "LNK_Stu_CI" lnk
where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",

from "Course" c
join "DBObjectBases" b_c on c."Id" = b_c."Id"

join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
join "CourseInstance" ci on ci."Id" = b_ci."Id",

lateral (select ci."MaximumPlaces" - "EnrolledStudents") x

我希望最右边的列是“MaximumPlaces” - “EnrolledStudents”的结果,但我正在努力让它发挥作用。目前,PG抱怨“入学学生”不存在 - 这正是“横向”的重点,不是吗?

select  b_ci."IdOwner",
ci."MinimumPlaces",
ci."MaximumPlaces",
(select count(*) from "LNK_Stu_CI" lnk
where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",
lateral (select "MaximumPlaces" - "EnrolledStudents") as "x"

from "Course" c
join "DBObjectBases" b_c on c."Id" = b_c."Id"

join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
join "CourseInstance" ci on ci."Id" = b_ci."Id"

如果我尝试内联在选择侧向条款(如上图所示),它被打乱过,给我一个语法错误 - 所以它在哪里去

谢谢,

亚当。

1 个答案:

答案 0 :(得分:3)

你错过了LATERAL的观点。它可以访问FROM子句中表中的列,但不能访问SELECT子句中定义的别名。

如果要访问SELECT子句中定义的别名,则需要使用FROM子句(AKA派生表)中的子查询或使用CTE (Common Table Expression)添加其他查询级别。由于PostgreSQL中的CTE充当优化范围,我强烈建议在这种情况下使用子查询,例如:

select
    -- get all columns on the inner query
    t.*,
    -- get your new expression based on the ones defined in the inner query
    t."MaximumPlaces" - t."EnrolledStudents" AS new_alias
from (
    select  b_ci."IdOwner",
    ci."MinimumPlaces",
    ci."MaximumPlaces",
    (select count(*) from "LNK_Stu_CI" lnk
    where lnk."FK_CourseInstanceId" = b_ci."Id") as "EnrolledStudents",

    from "Course" c
    join "DBObjectBases" b_c on c."Id" = b_c."Id"

    join "DBObjectBases" b_ci on b_ci."IdOwner" = b_c."Id"
    join "CourseInstance" ci on ci."Id" = b_ci."Id"
) t