2

我有一个联合查询,我想在联合查询“右侧”的选择语句中使用联合查询“左侧”中的选择结果。下面的查询正常工作(至少在 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
4

4 回答 4

4

您正在寻找公用表表达式

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

在您的第一个案例中:

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
于 2015-09-24T15:31:32.967 回答
1

group by当大多数数据库支持和时,为什么要这样做rollup?看来你想要这样的东西:

select x, count(*) as cnt
from <whatever>
group by x with rollup;
于 2015-09-24T15:32:19.957 回答
0

将query1结果放入临时表

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

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

select zz from temptable
union all
select count(zz) as zz from temptable 
于 2015-09-24T15:31:50.207 回答
0

您可能需要一个公用表表达式来重用 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
于 2015-09-24T15:32:50.710 回答