一些查询中的SQL错误相同

时间:2012-08-28 14:45:54

标签: sql compiler-errors ms-access-2010 calculated-columns

  

可能重复:
  Referencing field values between queries

我有3个类似的查询,在运行时给出同样的错误

You tried to execute a query that does not include the specified expression 'CompanyName' as part of an aggregate function

我有点理解这个问题,但我不知道如何解决它..以下是3个查询中的1个..

    SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, 
    (qb2.MPPOil-SUM(IIf(qb1.DatapointID=2003,
qb1.DatapointValue*1000000,
qb1.DatapointValue))) AS UnallocatedLossesOIL

    FROM PEBaseQuery AS qb1 
    INNER JOIN PE_MPPOilRevised AS qb2 
    ON qb1.AssetName = qb2.AssetName
    WHERE qb1.DatapointID In (2032,2034,2042,2036,2030,2028);

这是基于计算:

未分配损失= MPP - (GAS×1000000) - (Wellwork +年度停工维护+出口+工厂+水库损失)

我在另一个运行流畅的表中使用了类似的语法:S Heres代码:

SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, (qb1.DatapointValue/qb2.DatapointValue)*1000000 AS TRIPerMillionManHours
FROM HSEBaseQuery AS qb1 
INNER JOIN HSEBaseQuery AS qb2 
ON qb1.Assetname=qb2.AssetName
WHERE qb2.DatapointID=310005 AND qb1.DatapointID<>qb2.DatapointID;

为什么一个工作而另一个不工作?请帮忙!

1 个答案:

答案 0 :(得分:2)

第一个查询包含一个聚合函数,任何不是计算值的一部分的任何东西必须包含在group by子句中:

SELECT qb1.CompanyName
       , qb1.AssetName
       , qb1.Year
       , (qb2.MPPOil - SUM( IIf( qb1.DatapointID=2003,
                                 qb1.DatapointValue*1000000,
                                 qb1.DatapointValue))) AS UnallocatedLossesOIL
FROM  PEBaseQuery AS qb1 
      INNER JOIN PE_MPPOilRevised AS qb2 ON qb1.AssetName = qb2.AssetName
WHERE qb1.DatapointID In (2032,2034,2042,2036,2030,2028)
GROUP BY qb1.CompanyName
         , qb1.AssetName
         , qb1.Year
         , qb2.MPPOil;

正如HansUp所说,第二个查询不包含聚合函数sum(),因此不需要group by。