当来自Access中的不同表时,如何将一列的总和除以另一列的总和?

时间:2016-06-03 09:36:27

标签: sql ms-access

我想获取两个同名列的总和,除了它们来自两个不同的表(我被告知要多次合并它们,不幸的是我在这个问题上没有选择......)。我想将这两个求和值除以找出百分比变化。

下面是我编写的代码,它所做的只是无限加载。

SELECT SUM(C.[Market Value]) AS CSUM, 
       SUM(P.[Market Value]) AS PSUM, 
       CSUM/PSUM AS Percentage_Variation
FROM JanReport AS P,
     FebReport AS C;

我未能成功使用UNIONJOIN。看起来这个函数应该很容易实现,因为我已经能够按资产类求和%变量,我甚至可以得到两个列的总和来显示Totals函数。但是我似乎无法将它们分开。

有效的代码:

SELECT  SUM(FebReport.[Market Value]) AS Curr_Total_MV,
(
SELECT SUM(JanReport.[Market Value]) FROM JanReport
) AS Prior_Total_MV,
SUM(FebReport.[Market Value]) / 
(
SELECT SUM([Market Value]) FROM JanReport
) AS Percentage_Variation_In_Total_MV,
IIf(
0.9<Percentage_Variation_In_Total_MV AND 
Percentage_Variation_In_Total_MV<1.1,'Pass','Fail') AS Result
FROM FebReport;

1 个答案:

答案 0 :(得分:2)

内联SELECT应该在这里工作:

SELECT SUM([Market Value]) / (SELECT SUM([Market Value]) FROM JanReport) AS Percentage_Variation, 
FROM FebReport;

更新:每个只返回一行的两个子查询可以交叉连接以提供基础值:

SELECT
    [Current Market Value],
    [Previous Market Value],
    [Current Market Value] / [Previous Market Value] As Percentage_Variation
FROM
    (SELECT SUM([Market Value]) As [Current Market Value]  FROM FebReport) AS C,
    (SELECT SUM([Market Value]) As [Previous Market Value] FROM JanReport) AS P;