在PostgreSQL和GROUP BY中加入两个表

时间:2018-06-06 19:00:13

标签: sql postgresql

我在PostgreSQL中有以下表格:

表1:

MARKET        character varying 10
COST1         Number

MARKET       COST1      
A             3         
A             7
B             10 

表2:

MARKET        character varying"    10
COST2         Number

MARKET       COST2      
A             12         
A             13
B             15
B             15

我正在尝试生成一个报告,该报告将显示每个市场的cost1和cost1。这样的事情。

MARKET       COST1      COST2
A             10         25
B             10         30

我执行了以下查询:

select table1."MARKET", sum(table1."COST1"), sum(table2."COST2") 
from table1  inner join table2 on table1."MARKET" = table2."MARKET" GROUP 
BY(table1."MARKET")

我的OP如下。成本值超过应有的值:

MARKET       COST1      COST2
A             20         50
B             20         50

我做错了什么?任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

join 之前进行聚合。或者,使用union allgroup by

select market, sum(cost1) as cost1, sum(cost2) as cost2
from ((select market, cost1, 0 as cost2
       from table1
      ) union all
      (select market, 0, cost2
       from table2
      )
     ) mc
group by market;

答案 1 :(得分:1)

或者(你需要从第13行开始的代码; CTE在这里,以便我可以使用一些数据;忽略Oracle时尚的例子)。

SQL> with table1 (market, cost1) as
  2    (select 'a', 3 from dual union all
  3     select 'a', 7 from dual union all
  4     select 'b', 10 from dual
  5    ),
  6  table2 (market, cost2) as
  7    (select 'a', 12 from dual union all
  8     select 'a', 13 from dual union all
  9     select 'b', 15 from dual union all
 10     select 'b', 15 from dual
 11    )
 12  -- you need what follows:
 13  select x.market, sum(x.cost1) as cost1, sum(y.cost2) as cost2
 14  from (select a.market, sum(a.cost1) cost1
 15        from table1 a
 16        group by a.market) x
 17    join
 18       (select b.market, sum(b.cost2) cost2
 19        from table2 b
 20        group by b.market) y
 21    on x.market = y.market
 22  group by x.market;

M      COST1      COST2
- ---------- ----------
a         10         25
b         10         30

SQL>