如何以十进制值而不是null来获取它

时间:2013-08-21 13:52:31

标签: sql-server tsql

我试图在此查询中获取Decimal的值,但无法获得NULL值

SELECT 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.00

而不是此查询中的null

4 个答案:

答案 0 :(得分:4)

使用ISNULL内置功能:

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

答案 1 :(得分:2)

我甚至没有开始理解您正在进行的所有转换,但您只需在该表达式上使用ISNULL

SELECT ISNULL(<all your calculations here>,0)

答案 2 :(得分:1)

整个表达式的计算结果为NULL,因为您使用的是以下代码。

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

我要稍微分解一下,以便更容易理解。

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

因此将整个表达式包装在NULLIF(表达式0)中意味着它出现为NULL。

然后null通过计算的其余部分传播,并使整个表达式计算为NULL。

如果你希望它为0,你应该将整个表达式包装在ISNULL或COALESCE语句中,或者你可以删除NULLIF检查,尽管它有点不清楚你实际上想要实现的目标。

答案 3 :(得分:0)

SQL中的CAST太多了

如果您不想使用ISNULL,请使用CASE,因为您有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))

然而,除以零的任何东西都是未定义的或无穷大的:不是零。