Crosstab query with CTE returns error: relation "cte" does not exist
Crosstab query with CTE returns error: relation "cte" does not exist
我的 PostgreSQL 服务器上有两个模式,我正在尝试创建一个旋转的 table:
WITH cte AS (
SELECT l.fcid, t.fixture_code, COUNT(f.fixture_type_id) AS count
FROM aim.locations as l
JOIN aim.fixture_instances as f
ON l.id = f.location_id
JOIN aim.fixture_types as t
ON f.fixture_type_id = t.id
GROUP BY l.fcid, t.fixture_code
)
SELECT *
FROM lab.CROSSTAB('SELECT fcid, fixture_code, SUM(count) FROM cte group by 1,2 order by 1,2',
'Select DISTINCT fixture_code from cte order by 1')
AS CT (FCID integer, "fx1" bigint, "fx2" bigint)
ORDER BY fcid;
但是,我收到一个错误:
ERROR: relation "cte" does not exist
LINE 1: Select DISTINCT fixture_code from cte order by 1
当我只有一个架构时查询有效。
我使用 CTE,因此我可以使用查询创建视图。
这里有什么问题?
事实上,您根本不需要查询字符串参数的外部 SELECT
。添加的 sum(count)
在这个星座中没有任何改变。 CTE 中的查询已将最终结果提供给 crosstab()
。完全摆脱 CTE - 从而也解决了错误的直接原因:
SELECT *
FROM lab.crosstab(
$$
SELECT l.fcid, t.fixture_code, count(*) AS cnt
FROM aim.locations l
JOIN aim.fixture_instances f ON l.id = f.location_id
JOIN aim.fixture_types t ON f.fixture_type_id = t.id
GROUP BY 1,2
ORDER BY 1,2
$$
, $$VALUES ('fx1'), ('fx2')$$
) AS ct(fcid int, fx1 bigint, fx2 bigint);
其他一些事情:
如果您必须在列定义列表中拼出相应的列名,那么 运行 SELECT DISTINCT
毫无意义。将其替换为普通的 VALUES
表达式。
根据查询的定义,f.fixture_type_id
是 NOT NULL
,因此使用更快的等价物 count(*)
.
这里是基础知识:
- PostgreSQL Crosstab Query
我的 PostgreSQL 服务器上有两个模式,我正在尝试创建一个旋转的 table:
WITH cte AS (
SELECT l.fcid, t.fixture_code, COUNT(f.fixture_type_id) AS count
FROM aim.locations as l
JOIN aim.fixture_instances as f
ON l.id = f.location_id
JOIN aim.fixture_types as t
ON f.fixture_type_id = t.id
GROUP BY l.fcid, t.fixture_code
)
SELECT *
FROM lab.CROSSTAB('SELECT fcid, fixture_code, SUM(count) FROM cte group by 1,2 order by 1,2',
'Select DISTINCT fixture_code from cte order by 1')
AS CT (FCID integer, "fx1" bigint, "fx2" bigint)
ORDER BY fcid;
但是,我收到一个错误:
ERROR: relation "cte" does not exist LINE 1: Select DISTINCT fixture_code from cte order by 1
当我只有一个架构时查询有效。
我使用 CTE,因此我可以使用查询创建视图。
这里有什么问题?
事实上,您根本不需要查询字符串参数的外部 SELECT
。添加的 sum(count)
在这个星座中没有任何改变。 CTE 中的查询已将最终结果提供给 crosstab()
。完全摆脱 CTE - 从而也解决了错误的直接原因:
SELECT *
FROM lab.crosstab(
$$
SELECT l.fcid, t.fixture_code, count(*) AS cnt
FROM aim.locations l
JOIN aim.fixture_instances f ON l.id = f.location_id
JOIN aim.fixture_types t ON f.fixture_type_id = t.id
GROUP BY 1,2
ORDER BY 1,2
$$
, $$VALUES ('fx1'), ('fx2')$$
) AS ct(fcid int, fx1 bigint, fx2 bigint);
其他一些事情:
如果您必须在列定义列表中拼出相应的列名,那么 运行 SELECT DISTINCT
毫无意义。将其替换为普通的 VALUES
表达式。
f.fixture_type_id
是 NOT NULL
,因此使用更快的等价物 count(*)
.
这里是基础知识:
- PostgreSQL Crosstab Query