将结果合并到两个表中

时间:2013-06-06 04:34:29

标签: sql-server

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

将两个查询合并为一个以获得所需结果的正确方法是什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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