1

嗨,我正在尝试执行下面的 qry,并且在 subqry sum 行上不断收到“不能在表达式中具有聚合函数”错误。有什么办法可以使这项工作?

SELECT ID, 
    DateColumn, 
    Contamination, 
    BrokenGlass, 
    OtherReasons, 
    SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons) AS Total, 
    SUM(Contamination) / Total AS Expr1,
    (SELECT SUM(Contamination)/ SUM(SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons))
     FROM tbltest T2
     WHERE T2.ID <= T2.ID) AS RunningSum
FROM tbltest
GROUP BY ID, DateColumn, Contamination, BrokenGlass, OtherReasons
4

3 回答 3

3

我猜您正在使用基于 Expr1 的 MS-Access,请尝试以下操作。替换Total查询中的别名用法,您不能SUM(SUM())

SELECT ID, 
    DateColumn, 
    Contamination, 
    BrokenGlass, 
    OtherReasons, 
    SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons) AS Total, 
    SUM(Contamination) / (SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons)) AS Expr1,
    (SELECT SUM(Contamination)/ (SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons))
     FROM tbltest T2
     WHERE T2.ID <= tbltest.ID) AS RunningSum  -- I think you want T2.ID <= tbltest.ID not T2.ID <= T2.ID
FROM tbltest
GROUP BY ID, DateColumn, Contamination, BrokenGlass, OtherReasons
于 2012-08-08T14:12:35.123 回答
2

将您更改sum(sum())为仅使用加法运算符来计算结果总和:

--SUM(SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons)) 
(SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons)) 

此外,不要尝试在同一select子句中引用别名。要么使用子查询/派生表,要么只对“总计”重复所需的计算。

--SUM(Contamination) / Total AS Expr1
SUM(Contamination) / (SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons))
于 2012-08-08T14:12:50.087 回答
1
SELECT ID,  
    DateColumn,  
    Contamination,  
    BrokenGlass,  
    OtherReasons,  
    SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons) AS Total,  
    SUM(Contamination) / Total AS Expr1, 

    /* CHANGED THIS LINE */
    (SELECT SUM(Contamination)/ (SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons))
     FROM tbltest T2 
     WHERE T2.ID <= T2.ID) AS RunningSum 

FROM tbltest 
GROUP BY ID, DateColumn, Contamination, BrokenGlass, OtherReasons 

已编辑

结果不正确是一个与最初提出的问题完全不同的问题,我将不得不在黑暗中尝试一下,因为我对你的项目一无所知,但你去吧,也许它可以让你开始正确的方向。

SELECT ID,
    DateColumn,
    Contamination,
    BrokenGlass,
    OtherReasons,
    SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons) AS Total,
    SUM(Contamination) / Total AS Expr1,
    (
         SELECT SUM(Contamination)/ (SUM(Contamination) + SUM(BrokenGlass) + SUM(OtherReasons))
         FROM tbltest T2 
         WHERE T2.ID <= tbltest.ID
    ) AS RunningSum
FROM tbltest
GROUP BY ID, DateColumn, Contamination, BrokenGlass, OtherReasons
于 2012-08-08T14:13:20.820 回答