使用聚合函数作为表达式的一部分

时间:2014-06-11 15:20:35

标签: sql

简单的问题,我认为不可能将聚合函数用作表达式的一部分,但这基本上就是我想做的事情:

SELECT ((Sum(RESOURCES.[Hours Spent]*EMPLOYEES.[Employee Rate])) 
+ GRANTS.Overhead) AS [Estimated Development Cost]
FROM GRANTS 
INNER JOIN 
(EMPLOYEES 
INNER JOIN RESOURCES ON EMPLOYEES.[Employee Number] = RESOURCES.[Employee Number]) 
ON GRANTS.[Grant Program Number] = RESOURCES.[Grant Program Number];

在我尝试向其添加最后一个值(Grants.Overhead)之前,它完美地运行。我怎么能这样做?

感谢。

2 个答案:

答案 0 :(得分:2)

您必须将Grants.Overhead放在单独的查询中,因为每个组只计算一次。所以你走了:

SELECT T1.EDC + GRANTS.Overhead AS [Estimated Development Cost]
FROM   (SELECT   RESOURCES.[Grant Program Number] AS GPN,
             (Sum(RESOURCES.[Hours Spent] * EMPLOYEES.[Employee Rate])) AS EDC
    FROM     EMPLOYEES
             INNER JOIN
             RESOURCES
             ON EMPLOYEES.[Employee Number] = RESOURCES.[Employee Number]
    GROUP BY RESOURCES.[Grant Program Number]) AS T1
   INNER JOIN
   GRANTS
   ON GRANTS.[Grant Program Number] = T1.GPN;

答案 1 :(得分:0)

你也需要总结()开销,否则你将获得旧的"它不包含在聚合函数或GROUP BY子句中#34;错误。

这有效:

SELECT ((Sum(RESOURCES.[Hours Spent]*EMPLOYEES.[Employee Rate])) + sum(GRANTS.Overhead)) AS [Estimated Development Cost]
FROM GRANTS 
INNER JOIN (EMPLOYEES 
            INNER JOIN RESOURCES ON EMPLOYEES.[Employee Number] = RESOURCES.[Employee Number]) 
ON  GRANTS.[Grant Program Number] = RESOURCES.[Grant Program Number];