从MS Access中的2个表中求和

时间:2017-08-04 15:49:14

标签: sql ms-access select

我需要编写一个SQL查询,根据每个表(BrokerName)中公共字段的分组,将两个不同表(Insurance和Investments)中的字段(BranchRevenue)合并为一个数字。数据库是MS Access(我在下面的超链接中提供了一个示例结构)。

enter image description here

通过查看关于SO的类似帖子,我的理解是我需要从各个表(我可以做)中定义总和,然后使用DISTINCT或DISTINCTROW(我不能这样做)将它们聚合在一起。

以下是每个表的各个查询,它们通过BrokerName正确地对BranchRevenue进行求和。

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语句来完成此操作?

理想的解决方案是将两个表中的BranchRevenue正确地相加为每个BrokerName的一个数字,而不是从两个表中复制数据。

2 个答案:

答案 0 :(得分:1)

您可以在求和前使用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]

答案 1 :(得分:0)

你可以做一个简单的联合所有查询,然后分组

CanConvert