Search code examples
sqlsql-serversql-server-2012case

SQL Case Statement CASE calculation


My CASE statement defaults to default zero result regardless of the two conditions. I am not sure what the problem is.

,CASE 
            WHEN [Contract]='INIM' THEN 'Index' 
            WHEN [Contract]='BANK' THEN 'Index' 
        ELSE 'Single' 
    END AS 'I/S'
,CASE 
            WHEN 'I/S'='Index' THEN ([Quantity] *[Spot Price]*10)/1000000
            WHEN 'I/S'='Single' THEN ([Quantity] *[Spot Price]*100)/1000000
        ELSE 0
END AS [Notional (ZARm)]

Solution

  • The value 'I/S' is a string literal, and not the alias I/S. In any case, it is not possible to reuse this alias in the same SELECT. Here is a corrected version:

    CASE [Contract] WHEN 'INIM' THEN 'Index' 
                    WHEN 'BANK' THEN 'Index' 
                    ELSE 'Single' 
    END AS [I/S],
    CASE WHEN [Contract] IN ('INIM', 'BANK')
         THEN ([Quantity] *[Spot Price]*10) / 1000000
         ELSE ([Quantity] *[Spot Price]*100) / 1000000
    END AS [Notional (ZARm)]
    

    Note that, based on the first CASE expression, the ELSE 0 of the second CASE expression will never occur.