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

时间:2015-09-24 15:28:17

标签: sql postgresql union nested-query

我有一个union查询,我希望在union查询的“右侧”的select语句中使用union查询的“左侧”中的select结果。下面的查询正常工作(至少在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行:选择计数(zz)   作为来自query1的zz

有没有办法重写这个查询,所以query1只运行一次?

对Llama先生的回应进行了一些修改,效果很好,看起来像这样(注意添加“为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 个答案:

答案 0 :(得分:4)

您正在寻找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

答案 1 :(得分:1)

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

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

答案 2 :(得分: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 

答案 3 :(得分: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