2012-07-31 91 views
0

我有一個複雜的存儲過程,必須返回AmountSold的總和AmountSold和AmountCollected的總和AmountCollected,並且我也有既沒有銷售也沒有收集的行,而是已升級和UpgradedCollected colmns 。根據以下條件,該金額必須添加到已售出或收集或升級收集。我真的不明白語法錯誤,它寫着「關鍵字as不正確的語法錯誤」和「關鍵字then」。我在這裏做錯了什麼?先謝謝你!Select case with case然後給出錯誤

在前兩個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 

回答

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 case語句中有一些重複的邏輯,你可能簡化一下。

+0

謝謝!有效 :-) – Ram 2012-07-31 21:55:36