我試圖多次運行一個查詢 - 每次都有一個關於「where」語句的略有不同的規範。 我想寫一個單一的查詢,並要求數據庫逐步執行每個規格,並將相應的輸出保存爲csv.file。 我不知道如何開始。執行不同規格的PosgreSQL查詢並保存結果
的基本查詢如下:
SELECT
select id,
count(DISTINCT (a.id, c.publn_id)) as count
from a
join b on a.appln_id=b.appln_id
join c on b.publn_id=c.cit_id
left outer join d on c.publn_id=d.publn_id
group by id
我想運行下面的其他規格(注意在選擇和組修改通過,除了那裏的條件是必要的語句):
1.
SELECT
select id, c.auth,
count(DISTINCT (a.id, c.publn_id)) as count
from a
join b on a.appln_id=b.appln_id
join c on b.publn_id=c.cit_id
left outer join d on c.publn_id=d.publn_id
where (c.auth='EP' or c.auth='US')
group by id, c.auth
2.
SELECT
select id, d.categ,
count(DISTINCT (a.id, c.publn_id)) as count
from a
join b on a.appln_id=b.appln_id
join c on b.publn_id=c.cit_id
left outer join d on c.publn_id=d.publn_id
where c.auth='EP'
and (d.categ='X' or d.categ='Y')
group by id, d.categ
3.
SELECT
select id, d.categ,
count(DISTINCT (a.id, c.publn_id)) as count
from a
join b on a.appln_id=b.appln_id
join c on b.publn_id=c.cit_id
left outer join d on c.publn_id=d.publn_id
where c.auth='EP'
and (d.categ='E')
group by id, d.categ
4.
SELECT
select id,
count(DISTINCT (a.id, c.publn_id)) as count
from a
join b on a.appln_id=b.appln_id
join c on b.publn_id=c.cit_id
left outer join d on c.publn_id=d.publn_id
where c.auth='EP'
and (d.categ!='Y' and d.categ!='X' and d.categ!='E')
group by id
此外,每個規範將被用於查詢不同時間窗口(但我離開這些條件了現在)。
我想指定一個循環遍歷所有規格的單個查詢,然後自動保存結果。
'UNION ALL'可能是你想要的嗎?可能與'FROM'或CTE('WITH'查詢)中的子查詢結合? –
謝謝,我不確定'UNION ALL'如何提供幫助,你能舉個例子嗎?我正在考慮創建一個臨時表,然後用不同的條件指定不同的SELECTS。但是,我正在尋找一個解決方案,您只需指定一個基本的SELECT語句,其中包含一個包含不同條件的循環。我想得到的是每個規範的一個CSV文件:使用where =(c.auth ='EP'或c.auth ='US'),c.auth ='EP' 和( d.categ ='X'或d.categ ='Y')...,使用基本查詢開始循環(應用不同的條件),之後保存文件 –