PostgreSQL - 选择两个子查询的结果

时间:2013-09-26 21:01:15

标签: postgresql

我有两个复杂的查询,它们都是postgres中的子查询,其结果是:

q1_results = id , delta , metric_1
q2_results = id , delta , metric_2

我想结合查询的结果,因此外部查询可以访问:

results_a = id , delta , metric_1 , metric_2
results_b = id , delta , combined_metric

我无法弄清楚如何做到这一点。在线搜索会将我引导至UNION,但这会将指标保留在同一列中。我需要让他们分开。

1 个答案:

答案 0 :(得分:1)

您在问题和评论中提出的问题并不完全清楚,但听起来您可能正在寻找一系列合并语句的完整联接,例如:

-- create view at your option, e.g.:
-- create view combined_query as
select coalesce(a.id, b.id) as id,
       coalesce(a.delta, b.delta) as delta,
       a.metric1 as metric1,
       b.metric2 as metric2,
       coalesce(a.metric1,0) + coalesce(b.metric2,0) as combined
from   (...) as results_a a
full join (...) as results_b b on a.id = b.id -- and a.delta = b.delta maybe?