2013-06-06 198 views
1

two tables (Table1 and Table2)具有相同的列。將結果結合在兩個表中

Customerno, amount 

還有第三個表Customers與列:

Customerno, customername 

目前,以下兩個查詢運行,並使用Excel來源的組合的結果(VLOOKUP等)

Select a.customerno, b.customername, sum(a.amount) 
FROM Table1 a join customers b on a.Customerno = b.Customerno 
group by a.customerno, b.customername 


Select a.customerno, b.customername, sum(a.amount) 
FROM Table2 a join customers b on a.Customerno = b.Customerno 
group by a.customerno, b.customername 

將這兩個查詢合併爲一個以獲得所需結果的正確方法是?

回答

1
Select a.customerno, b.customername, sum(a.amount) 
FROM 
( 
    SELECT Customerno, amount FROM Table1 
    UNION ALL -- use this keep duplicates ie amounts from both tables 
    -- UNION -- will discard duplicates 
    SELECT Customerno, amount FROM Table2 
) a 
join customers b on a.Customerno = b.Customerno 
group by a.customerno, b.customername 
+0

謝謝。這有幫助。 – user1955215

0

您需要爲此使用UNION聲明。這是聯合這兩者的最簡單方法,你可以從這裏開始工作。

select * 
from 
(

Select a.customerno, b.customername, sum(a.amount) 
FROM Table1 a join customers b on a.Customerno = b.Customerno 
group by a.customerno, b.customername 

union -- or union all if you want to keep the duplicates 

Select a.customerno, b.customername, sum(a.amount) 
FROM Table2 a join customers b on a.Customerno = b.Customerno 
group by a.customerno, b.customername 
) P