How to get this in decimal value instead of null

后端 未结 4 1930
萌比男神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.

    0 讨论(0)
  • 2021-01-29 10:40

    I don't even start to understand all the conversions that you are doing, but you can just simply use ISNULL on that expression:

    SELECT ISNULL(<all your calculations here>,0)
    
    0 讨论(0)
  • 2021-01-29 10:43

    Use ISNULL built in function:

    ISNULL(CAST(CAST(CAST(SUM(CAST(0 AS INT)) AS DECIMAL(10, 2)) * 100 / CAST(NULLIF(SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)), 0) AS DECIMAL(10, 2)) AS DECIMAL(10, 2)) AS DECIMAL), 0) 
    

    http://technet.microsoft.com/es-es/library/ms184325.aspx

    0 讨论(0)
  • 2021-01-29 10:45

    Way too many CASTs in that SQL

    Use a CASE if you don't want to use ISNULL, which is needed because you have NULLIF

    SELECT 
      CAST(
        CASE
          WHEN SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)) = 0 THEN 0
          ELSE SUM(CAST(0 AS INT)) * 100.00 / (SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)) + SUM(CAST(0 AS INT)))
      END
      AS DECIMAL(10, 2))
    

    Howver, anything divided by zero is undefined or infinity: not zero.

    0 讨论(0)
提交回复
热议问题