您好我正在尝试执行下面的查询,并且我继续在子查询求和行上获得“表达式中没有聚合函数”错误。有什么方法可以做到这一点吗?
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
答案 0 :(得分: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
答案 1 :(得分: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))
答案 2 :(得分: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