连接两个具有相似列的表的总和不正确

时间:2017-08-10 05:10:13

标签: sql postgresql

鉴于我有两张表AB。这两个表格中包含col1col2等常用列。现在我想要得到的是A的总和和B的总和。以下是我目前正在使用的查询。

select 
col1 as W_NAME, 
col2 as I_NAME, 
NVL(sum(a.accepted),0) as RECEIVED_QTY,
NVL(sum(b.issue),0) as ISSUE_QTY

from TABLE1 a, TABLE2 b
where a.col1=b.col1 and a.col2=b.col2
group by col1, col2

数据以下列格式存储在表格中。

TABLE1

col1       col2          accepted
data1      val1          500
data1      val1          200
data2      val1          300
data2      val2          200

TABLE2

col1       col2          issue
data1      val1          100
data1      val1          50
data2      val2          100

我试图以下列格式获取数据,

col1     col2    accepted    issue
data1    val1     700        150
data2    val1     300        0
data2    val2     200        100

在我的查询中,我要么丢失一些行,要么显示的总和搞砸了。有什么建议。感谢。

1 个答案:

答案 0 :(得分:1)

with TABLE1_sum as (
select 
col1 as W_NAME, 
col2 as I_NAME, 
NVL(sum(a.accepted),0) as RECEIVED_QTY
from TABLE1 a
group by W_NAME, I_NAME
),
TABLE2_sum as (
select 
col1 as W_NAME, 
col2 as I_NAME, 
NVL(sum(b.issue),0) as ISSUE_QTY
from TABLE2 b
group by W_NAME, I_NAME
)
select coalesce(a.W_NAME,b.W_NAME) as W_NAME,
       coalesce(a.I_NAME,b.I_NAME) as I_NAME,
       coalesce(RECEIVED_QTY,0) as RECEIVED_QTY,
       coalesce(ISSUE_QTY,0) as ISSUE_QTY
from TABLE1_sum
full outer join TABLE2_sum on a.W_NAME = b.W_NAME and a.I_NAME = b.I_NAME