Possible Duplicate:
Referencing field values between queries
I have 3 similar queries that when run give me the same error
You tried to execute a query that does not include the specified expression 'CompanyName' as part of an aggregate function
I kind of understand the issue but i dont know how to resolve it.. Here are 1 of the 3 queries..
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);
This is based on the calculation:
Unallocated losses = MPP – (GAS × 1000000) – (Wellwork + Annual shutdown maintenance + Export + Plant + Reservoir losses)
I used similar syntax in another table which runs smoothly :S Heres the code:
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;
Why does one work and the other doesnt?? Please help!
The first query contains an aggregate function, and anything not part of the calculated value which is being summed must be contained within a group by clause:
As HansUp said, the second query doesn’t contain the aggregate function sum(), so no group by is required.