[英]How to use the results of a select in another select in a union query?
我有一個聯合查詢,我想在聯合查詢的“左側”中使用選擇的結果,在聯合查詢“右側”的選擇語句中。 下面的查詢工作正常(至少在 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
您正在尋找公共表表達式。
它們允許您定義結果並在查詢中多次使用它。
在你的拳頭情況下:
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
當大多數數據庫支持group by
和rollup
時,為什么會做這樣的事情? 看來你想要這樣的東西:
select x, count(*) as cnt
from <whatever>
group by x with rollup;
將 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
您可能需要一個公共表表達式來重用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.