2017-08-14 179 views
2

我有兩個表SalesCharges如何從兩個表中總結兩個不同的字段與一個字段是共同的

表有數據爲:

'Sales'          'Charges' 
SID F_AMT       SID   C_AMT 
1  100       1    10 
1  100       1    10 
1  100       1    20 
1  200       2    20 
2  200       2    10 
2  300       3    20 
4  300       3    30 
4  300       3    10 
4  300       5    20 
4  200       5    10 

我想要的輸出如下:

SID  Total_Fees  Total_charges 
1   500    40 
2   500    30 
3   0    60 
4   1100    0 
5   0    30 
+0

你用自己的嘗試過什麼? – Ritesh

+0

因此,您希望我們爲您編寫查詢,因此您沒有? –

+0

我會首先找到每個表的總數(你知道怎麼做,對嗎?提示:SUM()和GROUP BY),然後我會做兩個查詢的完整外連接。 – Boneist

回答

0

你可以使用條件彙總:

SELECT SID, 
     COALESCE(SUM(CASE WHEN t=1 THEN AMT END),0) AS Total_Fees, 
     COALESCE(SUM(CASE WHEN t=2 THEN AMT END),0) AS Total_Charges 
FROM (SELECT SID, F_AMT AS AMT, 1 AS t 
     FROM Sales 
     UNION ALL 
     SELECT SID, C_AMT AS AMT, 2 AS t 
     FROM Charges) sub 
GROUP BY SID 
ORDER BY SID; 

DB Fiddle Demo

1

假設你想這樣做,整個表格,這是最簡單的方法:

Select Sid 
      , Sum(f_amt) as total_fees 
      , Sum(c_amt) as total_charges 
From (select sid, f_amt, 0 as c_amt 
       From sales 
       Union all 
       select sid, 0 as f_amt, c_amt 
       From charges 
     ) 
Group by sid 
+0

非常感謝你的幫助。我不知道關於下面的方法.. 選擇SID,f_amt,0作爲c_amt 從銷售 聯盟所有 選擇SID,0作爲f_amt,c_amt 從收費 – Rohit

+0

如果這個答案已被證明有用,你應該考慮upvoting或接受它。接受的答案將StackOverflow作爲未來尋找者的一個來源。 – APC

1

使用full joinnvl()

select sid, nvl(sum(f_amt), 0) fees, nvl(sum(c_amt), 0) charges 
    from sales s 
    full join charges c using (sid) 
    group by sid 
    order by sid 

演示:

with sales(sid, f_amt) as (
    select 1, 100 from dual union all select 1, 100 from dual union all 
    select 1, 100 from dual union all select 1, 200 from dual union all 
    select 2, 200 from dual union all select 2, 300 from dual union all 
    select 4, 300 from dual union all select 4, 300 from dual union all 
    select 4, 300 from dual union all select 4, 200 from dual), 
charges (sid, c_amt) as (
    select 1, 10 from dual union all select 1, 10 from dual union all 
    select 1, 20 from dual union all select 2, 20 from dual union all 
    select 2, 10 from dual union all select 3, 20 from dual union all 
    select 3, 30 from dual union all select 3, 10 from dual union all 
    select 5, 20 from dual union all select 5, 10 from dual) 
select sid, nvl(sum(f_amt), 0) fees, nvl(sum(c_amt), 0) charges 
    from sales s 
    full join charges c using (sid) 
    group by sid 
    order by sid 

輸出:

SID  FEES CHARGES 
------ ---------- ---------- 
    1  1500  160 
    2  1000   60 
    3   0   60 
    4  1100   0 
    5   0   30 
相關問題