Sql 从MS Access中的两个表求和
我需要编写一个SQL查询,根据每个表(BrokerName)中公共字段的分组,将两个不同表(保险和投资)中的字段(BranchRevenue)相加为一个数字。数据库是MS Access(我在下面的超链接中提供了一个示例结构) 通过查看SO上的类似帖子,我的理解是,我需要从各个表中定义总和(我可以这么做),然后使用DISTINCT或DISTINCTROW(我不能这么做)将它们聚合在一起 下面是针对每个表的单独查询,这些查询通过BrokerName正确地求和BranchResidenceSql 从MS Access中的两个表求和,sql,ms-access,select,Sql,Ms Access,Select,我需要编写一个SQL查询,根据每个表(BrokerName)中公共字段的分组,将两个不同表(保险和投资)中的字段(BranchRevenue)相加为一个数字。数据库是MS Access(我在下面的超链接中提供了一个示例结构) 通过查看SO上的类似帖子,我的理解是,我需要从各个表中定义总和(我可以这么做),然后使用DISTINCT或DISTINCTROW(我不能这么做)将它们聚合在一起 下面是针对每个表的单独查询,这些查询通过BrokerName正确地求和BranchResidence SELE
SELECT Investments.BrokerName AS [BrokerName],Sum(Investments.BranchRevenue) as [BranchRevenue]
FROM Investments WHERE ( ((Investments.Ledger = 'Actual') AND (Investments.Year1 = 2017) AND (Investments.Period = 6) AND (Investments.Branch = 'Toronto') ) )
GROUP BY Investments.BrokerName
SELECT Insurance.BrokerName AS [BrokerName],Sum(Insurance.BranchRevenue) as [BranchRevenue]
FROM Insurance WHERE ( ((Insurance.Ledger = 'Actual') AND (Insurance.Year1 = 2017)
AND (Insurance.Period = 6) AND (Insurance.Branch = 'Toronto') ) )
GROUP BY Insurance.BrokerName
如何使用一条SQL语句来实现这一点
理想的解决方案是将两个表中的BranchResidence正确相加为每个BrokerName的一个数字,同时不复制两个表中的数据。您可以执行简单的union all查询,然后进行分组
select BrokerName, sum(BranchRevenue) from (
select * from Insurer
where...
union all
select * from Investments
where ...)
group by BrokerName
在求和之前,您可以使用
union all
组合两个表的结果:
SELECT [BrokerName], SUM([BranchRevenue])
FROM (SELECT Investments.BrokerName AS [BrokerName],
Investments.BranchRevenue AS [BranchRevenue]
FROM Investments
WHERE Investments.Ledger = 'Actual' AND
Investments.Year1 = 2017 AND
Investments.Period = 6 AND
Investments.Branch = 'Toronto'
UNION ALL
SELECT Insurance.BrokerName AS [BrokerName],
Insurance.BranchRevenue AS [BranchRevenue]
FROM Insurance
WHERE Insurance.Ledger = 'Actual' AND
Insurance.Year1 = 2017 AND
Insurance.Period = 6 AND
Insurance.Branch = 'Toronto'
) t
GROUP BY [BrokerName]
这个解决方案非常有效。非常感谢您的快速帮助。=)