How to get this in decimal value instead of null

后端 未结 4 1942
萌比男神i
萌比男神i 2021-01-29 10:13

i am trying to get value in Decimal in this query but unable to get i am getting NULL Value

SELECT CAST(CAST(CAST(SUM(CAST(0 AS INT)) AS DECIMAL(10, 2)) * 100 
         


        
4条回答
  •  醉梦人生
    2021-01-29 10:37

    The entire expression is evaluating to NULL because you are using the following code.

    NULLIF  (
        SUM (   
            CAST(0 AS INT)
        ) + 
        SUM(    
            CAST(0 AS INT)
        ) + 
        SUM(    CAST(0 AS INT)
        ), 
        0
    ) 
    

    I'm going to break this down a little to make it easier to understand.

    CAST(0 AS INT) evaluates to 0
    
    SUM( CAST( 0 AS INT ) ) evaluates to 0
    
    SUM( CAST(0 AS INT) ) + 
    SUM( CAST(0 AS INT) ) + 
    SUM( CAST(0 AS INT) ) also evaluates to 0
    

    So wrapping that whole expression in a NULLIF (expression, 0) means it comes out as NULL.

    That null then propagates through the rest of the calculation and causes the whole expression to evaluate to NULL.

    If you want it to be 0 you should wrap the whole expression in a ISNULL or a COALESCE statement or you could remove the NULLIF check although it's a little unclear what you are actually trying to achieve.

提交回复
热议问题