0

可能重复:
在查询之间引用字段值

我有 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) - (油井 + 年度停机维护 + 出口 + 工厂 + 水库损失)

我在另一个运行平稳的表中使用了类似的语法:S 下面是代码:

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;

为什么一个有效而另一个无效?请帮忙!

4

1 回答 1

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。

于 2012-08-28T15:10:52.430 回答