选择Statement with case,然后给出错误

时间:2012-07-31 17:09:21

标签: sql sql-server tsql

我有一个复杂的存储过程,必须将AmountSold的Sum返回为AmountSold,AmountCollected的总和为AmountCollected,并且我的行既没有Sold也没有收集,而是具有Upgraded和UpgradedCollected colmns。根据以下条件,该金额必须添加到已售出或已收集或已升级收集。我真的不明白语法错误,其中“关键字附近的语法错误不正确”和“关键字然后”。我在这做错了什么?提前谢谢!

在前2个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

1 个答案:

答案 0 :(得分:2)

不幸的是,SQL case语句不能像你尝试使用它们一样工作。在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案例陈述中有一些重复的逻辑你可以简化。