2017-08-04 24 views
1

我需要编写一个SQL查询,根据每个表中的公共字段的分组将总共来自两个不同表(保险和投资)的字段(BranchRevenue)组成一个数字的SQL查询(BrokerName )。数据库是MS Access(我在下面的超链接中提供了一个示例结构)。从MS Access中的2个表中总结

enter image description here

我从看的如此相似职位的理解是,我需要定义从各个表的款项(这是我可以做的),然后使用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的一个数字,而不从两个表中复制数据。

回答

0

你可以做一个简单的UNION ALL查询,然后组

select BrokerName, sum(BranchRevenue) from (
select * from Insurer 
    where... 
union all 
select * from Investments 
    where ...) 
group by BrokerName 
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] 
+0

该解决方案完美地工作。非常感谢您的快速帮助。 =) – darryl444