【问题标题】:Summing from 2 Tables in MS Access从 MS Access 中的 2 个表中求和
【发布时间】:2017-08-04 15:49:13
【问题描述】:

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

通过查看 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 的一个数字,而不是从两个表中复制数据。

【问题讨论】:

    标签: sql ms-access select


    【解决方案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]
    

    【讨论】:

    • 这个解决方案效果很好。非常感谢您的快速帮助。 =)
    【解决方案2】:

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

    select BrokerName, sum(BranchRevenue) from (
    select * from Insurer
      where...
    union all
    select * from Investments
      where ...)
    group by BrokerName
    

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      相关资源
      最近更新 更多