我有一个通过执行以下计算来计算单位重量(g)的列
SELECT ROUND (Weight,0) / nullif ([Units per Carton],0) * 454 AS [Unit Weight (g)]
FROM [Item Master]
我使用nullif来消除除以零。但我也想在除数上使用Round()
我试过这个:
SELECT ROUND (Weight,0) / nullif(Round([Units per Carton],0) * 454) AS [Unit Weight (g)]
FROM [Item Master]
我试过这个:
SELECT nullif (ROUND (Weight,0) / (Round([Units per Carton],0) * 454) AS [Unit Weight (g)]
FROM [Item Master]
错误: 消息156,第15级,状态1,第1行 关键字“AS”附近的语法不正确。
**那么我如何在除数上结合圆函数和nullif? **
新编码
SELECT ROUND (Weight,0) / nullif([Units per Carton],0) * 454 AS [Unit Weight (g)]
FROM [Item Master]
SELECT ROUND (Weight / NULLIF([Units per Carton],0),0) * 454 AS [Unit Weight (g)]
FROM [Item Master]
我尝试了以上内容,我得到的结果就是这个 - > picture
结果不同我希望结果为151,227和227,但这些结果会被0代替。
答案 0 :(得分:0)
Null永远不应该是红利。您将无法获得逻辑上一致的结果除以空值。请记住,null根本不是一个值,它只是'未知'的标记。 (并且null与'null'不同。)
您可以改为尝试分支条件。
SELECT 454 * ROUND( (Weight * 1.0) / CASE WHEN [Units per Carton] = 0 THEN -1
ELSE [Units per Carton] END , 0) AS [Unit Weight (g)]
任何结果为负的权重都是0的替代。
或者,简而言之:
SELECT @Quotient = CASE WHEN @divisor = 0 THEN NULL
ELSE @dividend / @divisor END