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

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

4

2 回答 2

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
于 2013-06-06T04:41:20.860 回答
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
于 2013-06-06T08:31:09.927 回答