challengeAccepted
challengeAccepted

Reputation: 7590

Select Statement with case and then gives error

I have a complex stored procedure that has to return Sum of AmountSold as AmountSold and sum of AmountCollected as AmountCollected and also i have rows that has neither Sold nor collected and instead has Upgraded and UpgradedCollected colmns. Depending on the below conditions, that amount has to added into Sold or collected or UpgradedCollected. I dont really understand the syntax error which says "Incorrect Syntax error near keyword as" and for "keyword then". What am i doing wrong here? Thank you in advance!

In the first 2 if's, i have written different code assuming either of them should be correct. This is in 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

Upvotes: 0

Views: 159

Answers (1)

csm8118
csm8118

Reputation: 1213

Unfortunately SQL case statements don't work the way you're trying to use them. When used in a SELECT statement like how you are using them, each case expression can only define one column at a time. So, something like the following should work for you.

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

You'll notice when you write it this way there is a bit of duplicated logic in the AmountSold case statement that you can probably simplify.

Upvotes: 2

Related Questions