0

我有一个复杂的存储过程,它必须将 AmountSold 的总和作为 AmountSold 返回,将 AmountCollected 的总和作为 AmountCollected 返回,而且我的行既没有 Sold 也没有收集,而是具有 Upgraded 和 UpgradedCollected 列。根据以下条件,该金额必须添加到 Sold、collected 或 UpgradedCollected。我真的不明白“关键字附近的语法错误”和“关键字那么”的语法错误。我在这里做错了什么?先感谢您!

在前两个 if 中,我编写了不同的代码,假设它们中的任何一个都应该是正确的。这是在 SQL 05 中。

Select sum(cast(RDC.AmountSold as numeric(10,2))) as AmountSold, 
sum(cast(RDC.AmountCollected as numeric(10,2))) as AmountCollected,


case when RDC.AmountUpgraded = RDC.AmountUpgradedCollected
        then sum(cast((AmountSold + RDC.AmountUpgraded)as numeric(10,2))) as AmountSold
        and sum(cast((AmountCollected + RDC.AmountUpgradedCollected)as numeric(10,2))) as AmountCollected
        else if RDC.AmountUpgraded > RDC.AmountUpgradedCollected
        then AmountSold = AmountSold + RDC.AmountUpgraded 
        and AmountCollected = AmountCollected + RDC.AmountUpgradedCollected
        else
        then AmountSold = AmountSold + RDC.AmountUpgraded 
        and AmountCollected = AmountCollected + RDC.AmountUpgraded 
        and AmountUpgradedCollected = AmountUpgradedCollected + (RDC.AmountUpgradedCollected - RDC.AmountUpgraded)
        as AmountUpgradedCollected

end
4

1 回答 1

2

不幸的是,SQL 案例语句不能按照您尝试使用它们的方式工作。当在SELECT语句中使用它们时,每个 case 表达式一次只能定义一列。因此,以下内容应该适合您。

Select sum(cast(RDC.AmountSold as numeric(10,2))) as AmountSold, 
sum(cast(RDC.AmountCollected as numeric(10,2))) as AmountCollected,

SUM(CASE WHEN RDC.AmountUpgraded = RDC.AmountUpgradedCollected
  THEN CAST(AmountSold + RDC.AmountUpgraded as numeric(10,2))
  ELSE CAST(AmountSold + RDC.AmountUpgraded as numeric(10,2))
END) AS AmountSold,

SUM(CASE WHEN RDC.AmountUpgraded = RDC.AmountUpgradedCollected
  THEN cast(AmountCollected + RDC.AmountUpgradedCollected as numeric(10,2))
  ELSE cast(AmountCollected + RDC.AmountUpgraded  as numeric(10,2))
END) AS AmountCollected

你会注意到,当你用这种方式编写它时,AmountSold 案例语句中有一些重复的逻辑,你可以简化它们。

于 2012-07-31T17:26:19.430 回答