Sql server 将结果合并到两个表中
有两个列相同的表(表1和表2)Sql server 将结果合并到两个表中,sql-server,Sql Server,有两个列相同的表(表1和表2) Customerno, amount 第三个表Customers,包含以下列: Customerno, customername 目前,运行以下两个查询,并使用Excel(vlookup等)导出组合结果 将两个查询合并为一个查询以获得所需结果的正确方法是什么?您需要为此使用语句。这是将这两者结合起来的最简单方法,你可以从这里开始工作 Select a.customerno, b.customername, sum(a.amount) FROM (
Customerno, amount
第三个表Customers
,包含以下列:
Customerno, customername
目前,运行以下两个查询,并使用Excel(vlookup等)导出组合结果
将两个查询合并为一个查询以获得所需结果的正确方法是什么?您需要为此使用语句。这是将这两者结合起来的最简单方法,你可以从这里开始工作
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
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
您需要为此使用语句。这是将这两者结合起来的最简单方法,你可以从这里开始工作
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