我试图多次运行一个查询 - 每次都有一个关于“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')...,使用基本查询开始循环(应用不同的条件),之后保存文件 –