在查询之间引用字段值

时间:2012-08-26 16:42:19

标签: sql ms-access-2010 calculated-field

我试图通过使用查询在Access中创建计算。目前,一个查询计算'MPP Oil'(最大生产潜力)的值,另一个查询需要使用该值来计算'未分配的损失'。这些计算使用来自基本查询“PEBaseQuery”的公司/资产/年度数据。用于计算未分配损失的其他输入值使用ID引用...但是我的代码似乎有些问题,请帮忙!

SELECT 
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    (qb3.MPPOilRevised 
     - SUM(qb1.DatapointValue) 
     - SUM(qb2.DatapointValue * 1000000)) AS Result
FROM 
    ((PEBaseQuery AS qb1 
    INNER JOIN PEBaseQuery AS qb2 
    ON qb1.Year = qb2.Year AND qb1.AssetName=qb2.AssetName)
    INNER JOIN PE_MPPOilRevised AS qb3 
    ON qb1.Year = qb3.Year AND qb1.AssetName=qb3.AssetName)
WHERE 
    qb1.DatapointID in (2033, 2035, 2043, 2037, 2031) 
AND qb2.DatapointID=2003
GROUP BY qb1.CompanyName, qb1.AssetName, qb1.Year;

2 个答案:

答案 0 :(得分:1)

根据您在评论中提到的错误:

  

错误'您尝试执行的查询不包含指定表达式'CompanyName'作为聚合函数的一部分'

使用聚合函数要求您按SELECT列表中除聚合列之外的列进行分组。

修改

我认为这就是你要找的东西:

SELECT
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    qb3.MPPOilRevised - TotalDataPointValue - TotalDataPointValueFactor
FROM
    ((
        SELECT 
            qb1.CompanyName, 
            qb1.AssetName, 
            qb1.Year, 
            SUM(qb1.DatapointValue) 'TotalDataPointValue',
            SUM(qb2.DatapointValue * 1000000) 'TotalDataPointValueFactor'
        FROM 
            (PEBaseQuery AS qb1 
            INNER JOIN PEBaseQuery AS qb2 
            ON qb1.Year = qb2.Year AND qb1.AssetName = qb2.AssetName)
        WHERE 
            qb1.DatapointID in (2033, 2035, 2043, 2037, 2031) 
        AND qb2.DatapointID = 2003
        GROUP BY qb1.CompanyName, qb1.AssetName, qb1.Year
    ) qb1
    INNER JOIN PE_MPPOilRevised AS qb3 
    ON qb1.Year = qb3.Year AND qb1.AssetName=qb3.AssetName)

答案 1 :(得分:0)

创建聚合查询时,必须按每个选定的字段聚合或分组。

尝试:

SELECT 
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    (qb3.MPPOilRevised 
     - SUM(qb1.DatapointValue) 
     - SUM(qb2.DatapointValue * 1000000)) AS Result
FROM 
    PEBaseQuery AS qb1 
    INNER JOIN PEBaseQuery AS qb2 
    ON qb1.Year = qb2.Year AND qb1.Assetname=qb2.AssetName
    INNER JOIN PE_MPPOilRevised AS qb3 
    ON qb1.Year = qb3.Year AND qb1.Assetname=qb3.AssetName
WHERE 
    qb1.DatapointID in (2033, 2035, 2043, 2037, 2031) 
AND qb2.DatapointID=2003;
GROUP BY
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year