带有3个备选方案的SQL IF语句

时间:2012-08-26 17:03:55

标签: sql if-statement ms-access-2010 calculated-columns

嘿伙计们我真的可以使用一些帮助来编写这个IF语句!我设法适应了两个条件,不确定第三个(计算)如何适合。这是伪代码中的计算;

IF Producer_Type = 'Oil', Unallocated OIL&GAS = UnallocatedLossesOIL
IF Producer_Type = 'Gas', Unallocated OIL&GAS = UnallocatedLossesGAS
ELSE Unallocated OIL GAS = UnallocatedLossesOIL(MPPOil ÷ (MPPOil + MPPGas)) + 
UnallocatedLossesGAS(MPPGas ÷ (MPPOil + MPPGas))

这是我的代码:

SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, 
IIf(qb1.Producer_Type='Oil',qb1.DatapointValue, qb2.DatapointValue) AS UnallocatedOilGas
FROM PEBaseQuery AS qb1 INNER JOIN PEBaseQuery AS qb2 ON qb1.Assetname=qb2.AssetName
WHERE qb1.DatapointID=2026 And qb2.DatapointID=2027;

其中,2026的DatapointID为UnallocatedLossesOIL,而2027为UnallocatedLossesGAS。计算需要参考MPPOil和MPPGas值(与特定公司/资产/年份相关,这是两个独立查询的结果......任何帮助都会非常感激!对不起,如果其中一些没有意义..

1 个答案:

答案 0 :(得分:1)

如何嵌套if条件?我的意思是,如果可能,这应该有效:

SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, 
IIf(qb1.Producer_Type='Oil', qb1.DatapointValue, 
  IIF(qb1.Producer_Type='Gas', qb2.DatapointValue,
   qb1.DatapointValue * (MPPOil / (MPPOil + MPPGas)) + 
   qb2.DatapointValue * (MPPGas / (MPPOil + MPPGas)) )) AS UnallocatedOilGas
FROM PEBaseQuery AS qb1 INNER JOIN PEBaseQuery AS qb2 ON qb1.Assetname=qb2.AssetName
WHERE qb1.DatapointID=2026 And qb2.DatapointID=2027;

关于MPPGasMPPOil的值,我不知道在哪里可以找到它们,所以请将它们保留原样。 我希望这有效。