在Postgresql中水平加入两个选择查询

时间:2014-12-16 07:11:17

标签: sql postgresql-9.1

我有以下两个问题:

查询#1:

(SELECT 
    pl.c_project_Id, pl.c_projectphase_Id, pl.c_projecttask_Id, pl.m_product_Id,
    pj.name as projectname, ph.name as phasename, pt.name as taskname, pd.name as prodname,
    round(pl.plannedqty, 2) as planqty, round(pl.plannedprice, 2) as planrate,
    round(pl.plannedamt, 2) as planamt

FROM adempiere.c_projectline pl
LEFT JOIN adempiere.c_project pj ON pl.c_project_id = pj.c_project_id
LEFT JOIN adempiere.c_projectphase ph ON pl.c_projectphase_id = ph.c_projectphase_id
LEFT JOIN adempiere.c_projecttask pt ON pl.c_projecttask_id = pt.c_projecttask_id
LEFT JOIN adempiere.m_product pd ON pl.m_product_id = pd.m_product_id
WHERE pl.c_project_id = 1000001 AND pl.ad_client_id = 1000000
ORDER BY ph.c_projectphase_id, pt.c_projecttask_id)

输出为:11列和16行

查询#2:

(SELECT
    fa.c_project_id, fa.c_projectphase_id, fa.c_projecttask_id, fa.m_product_id,
    pj.name as costprojectname, ph.name as costphasename, pt.name as costtaskname,
    pd.name as costprodname,
    abs(fa.qty) as costqty, round((fa.amtacctdr/fa.qty), 2) as costrate,
    round(sum(fa.amtacctdr), 0) as costamt

FROM adempiere.fact_acct fa
LEFT JOIN adempiere.c_project pj ON fa.c_project_id = pj.c_project_id
LEFT JOIN adempiere.c_projectphase ph ON fa.c_projectphase_id = ph.c_projectphase_id
LEFT JOIN adempiere.c_projecttask pt ON fa.c_projecttask_id = pt.c_projecttask_id
LEFT JOIN adempiere.m_product pd ON fa.m_product_id = pd.m_product_id
WHERE  fa.c_project_id = 1000001 AND (fa.gl_category_id = 1000006 OR fa.gl_category_id = 1000005)
AND fa.qty > 0 AND fa.c_project_id is not null
GROUP BY fa.m_product_id, fa.c_project_id, fa.c_projectphase_id, fa.c_projecttask_id,
        fa.qty, fa.amtacctdr,
        pj.name, ph.name, pt.name, pd.name)

输出为:11列和6行

我希望水平加入这些查询,显示所有列,但行不应重复。当我应用union来加入它们时,结果会显示重复的行。我该如何处理这个问题?

1 个答案:

答案 0 :(得分:7)

你应该可以加入这样的查询:

select * from
  (
   <your first query here>
  ) tbl1
  join (
    <your second query here>
  ) tbl2
  on tbl1.c_project_Id = tbl2.c_project_Id
 and tbl1.c_projectphase_Id = tbl2.c_projectphase_Id -- you might add or
 and tbl1.c_projecttask_Id  = tbl2.c_projecttask_Id  -- remove join criteria 
 and tbl1.m_product_Id = tbl2.m_product_Id           -- here