它看起来像你需要的不是这种复杂的聚合查询。例如。
select companyName, assetName, year,
Sum(DatapointValue) as MPPOilRevised
from PEBaseQuery
where DatapointID in (2032, 2034, 2042, 2036)
group by companyName, assetName, year
唯一的问题是第一个数据点乘以1000000。你可以尝试IIF
为:
select companyName, assetName, year,
Sum(IIf(DatapointID=2003,DatapointValue*1000000,DatapointValue)) as MPPOilRevised
from PEBaseQuery
where DatapointID in (2032, 2034, 2042, 2036)
group by companyName, assetName, year
另外,请尝试这种“疯狂”的查询,有子查询这个特定DatapointID,没有IIF
:
select companyName, assetName, year, SUM(DatapointValue)
+ (select SUM(DatapointValue * 1000000) from PEBaseQuery q2
where q2.companyName = q1.companyName
and q2.assetName= q1.assetName
and q2.year= q1.year
and q2.DatapointID = 2003
group by companyName, assetName, year)
from PEBaseQuery q1
where DatapointID in (2032, 2034, 2042, 2036)
group by companyName, assetName, year
更新“生产最大潜力”。请尝试以下操作:
select b.companyName, b.assetName, IIf(b.calculationResult > mp.calculationResult,b.calculationResult,mp.calculationResult) as MPPOilRevised
from
(select companyName, assetName, year, Sum(IIf(DatapointID=2003,DatapointValue*1000000,DatapointValue)) as calculationResult
from PEBaseQuery
where DatapointID in (2032, 2034, 2042, 2036)
group by companyName, assetName, year) b --Base
left join
(select companyName, assetName, year,
Sum(DatapointValue) as calculationResult
from PEBaseQuery
where DatapointID = 2218
group by companyName, assetName, year) mp -- Max Potential
on b.companyName= mp.companyName
and b.assetName = mp.assetName
and b.year = mp.year
带减法逻辑的计算示例。 更新与最后的疯狂SQL。另请注意,我将与应用逻辑或存储过程去这样那样的事情:
select b.companyName, b.assetName, IIf(b.calculationResult > mp.calculationResult,b.calculationResult,mp.calculationResult) as MPPOilRevised
from
(select companyName, assetName, year, SUM(DatapointValue)
+ (select SUM(DatapointValue * 1000000) from PEBaseQuery q2
where q2.companyName = q1.companyName
and q2.assetName= q1.assetName
and q2.year= q1.year
and q2.DatapointID = 2003
group by companyName, assetName, year)
- (select SUM(DatapointValue) from PEBaseQuery q2
where q2.companyName = q1.companyName
and q2.assetName= q1.assetName
and q2.year= q1.year
and q2.DatapointID = 2029
group by companyName, assetName, year)
from PEBaseQuery q1
where DatapointID in (2032, 2034, 2042, 2036)
group by companyName, assetName, year) b --Base
left join
(select companyName, assetName, year,
Sum(DatapointValue) as calculationResult
from PEBaseQuery
where DatapointID = 2218
group by companyName, assetName, year) mp -- Max Potential
on b.companyName= mp.companyName
and b.assetName = mp.assetName
and b.year = mp.year
尝试不上不下'qbX.DatapointValue'操作数为'(SELECT qbX.DatapointValue FROM ... WHERE ... 。)AS ExprX'。 – EthanB
一些单独的问题..为什么你需要这个乘数为1000000的第一个DatapointValue?它看起来很奇怪,因为这些值来自一列。我认为如果没有它,就会让整个查询变得更简单。 – udalmik
乘以百万是因为我需要每百万桶油的价值 – Magda