Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 横向查询语法_Postgresql - Fatal编程技术网

Postgresql 横向查询语法

Postgresql 横向查询语法,postgresql,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"

我正试图让你在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"
如果我尝试在select中内联lateral子句(如上图所示),它也会被打乱,并给我一个语法错误——那么它会去哪里呢

谢谢


亚当。

你没有抓住侧方的重点。它可以访问FROM子句中表中的列,但不能访问SELECT子句中定义的别名

如果要访问SELECT子句中定义的别名,则需要添加另一个查询级别,可以使用FROM子句(也称为派生表)中的子查询,也可以使用。由于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

我不太明白。如果我把“横向”行注释掉,它就行了。你甚至需要
lateral
在这里吗?将
(ci.“MaximumPlaces”-“EnrolledStudents”)作为“SomeLabel”
不起作用吗?错误:列“EnrolledStudents”不存在-无法引用生成的列。正如我所说的,我认为这就是横向的目的——它相当于sql server的交叉应用程序。Bing!一盏灯亮了!谢谢你,马修斯。(感谢之前的海报提供的帮助。)