我有一个联合查询,我想在联合查询“右侧”的选择语句中使用联合查询“左侧”中的选择结果。下面的查询正常工作(至少在 postgres 上),但我运行 query1 2 次,一次作为 query1,再次作为 sameAsQuery1。
select x as zz from (select 69 as x) as query1
union all
select count(zz) as zz from
(select x as zz from (select 69 as x) as sameAsQuery1) as query2
我想做这样的事情,所以我不必运行 query1 2 次,但它不起作用:
select x as zz from (select 69 as x) as query1
union all
select count(zz) as zz from query1
我收到此错误消息:
错误:关系“query1”不存在第 3 行:从 query1 中选择 count(zz) 作为 zz
有没有办法重写这个查询,所以 query1 只运行一次?
对 Llama 先生的回应稍作修改,效果很好,看起来像这样(注意添加了“as q2”):
WITH
query1 AS
(
SELECT x AS zz FROM (SELECT 69 AS x) as q2
)
SELECT zz FROM query1
UNION ALL
SELECT COUNT(zz) AS zz FROM query1