I have a union query, where I want to use the results of the select in the "left side" of the union query, in the select statement on the "right side" of the union query. The query below works correctly (on postgres at least), but I am running query1 2 times, once as query1, and again as 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
I would like to do something like this so I don't have to run query1 2 times, but it doesn't work:
select x as zz from (select 69 as x) as query1
union all
select count(zz) as zz from query1
I get this error message:
ERROR: relation "query1" does not exist LINE 3: select count(zz) as zz from query1
Is there a way to rewrite this query so query1 only runs once?
Minor modification to Mr. Llama's response worked quite well, it looks like this (Note the addition of "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