如何在联合查询中使用另一个 select 中的 select 的结果?

How to use the results of a select in another select in a union query?

我有一个联合查询,我想在联合查询的 "left side" 中使用 select 的结果,在 [=27] 的 select 语句中=] 的联合查询。下面的查询工作正常(至少在 postgres 上),但我 运行ning 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

我想做这样的事情,这样我就不必 运行 查询 1 2 次,但它不起作用:

select x as zz from (select 69 as x) as query1
union all
select count(zz) as zz from query1

我收到此错误消息:

ERROR: relation "query1" does not exist LINE 3: select count(zz) as zz from query1

有没有办法重写此查询,使查询 1 仅 运行 一次?

对 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

您正在寻找 common table expressions

它们允许您定义结果并在查询中多次使用它。

在你的第一个案例中:

WITH
query1 AS
(
    SELECT x AS zz FROM (SELECT 69 AS x)
)
SELECT zz FROM query1
UNION ALL
SELECT COUNT(zz) AS zz FROM query1

将query1结果放入temp table

select x as zz from (select 69 as x) as query1 into temptable

现在在第二个查询中使用临时 table

select zz from temptable
union all
select count(zz) as zz from temptable 

为什么大多数数据库都支持 group byrollup,为什么要做这样的事情?看来你想要这样的东西:

select x, count(*) as cnt
from <whatever>
group by x with rollup;

您可能需要一个通用 Table 表达式来重用 SELECT:

with cte as
( select x as zz from (select 69 as x) as query1 )
select * from cte
union all
select count(zz) as zz from cte