2017-08-10 31 views
0

鑑於我有兩個表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

你需要執行總和,然後加入 – Steven

+0

非常感謝你,我只是還沒喝過我的咖啡。 – unkn0wn

回答

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 
相關問題