2014-10-06 68 views
4

嗨,我有一些问题SQL检查是零或空

需要检查是列空或零,如果事情做错了一些算法

这是一个表:

col1 col2 col3 col4 
1  0  3376 0 
2  600  null 14468.5714 
3  null 0  0 
4  600  3376 null 

COALESCE不适用于零“0”值,case其太大

需要实现一些

, CAST(COALESCE(col2, (col3/7), (col4/30)) as money) col2 
, CAST(COALESCE(col3, (col2*7), (col4/30*7))as money) col3 
, CAST(COALESCE(col4, (col3/7*30),(col2*30))as money) col4 

如何以最快的方式解决这个问题。 THANX

+0

你是说,你需要遇到0对空进行区分?我认为“null或0”可以被模糊地解释。 – Kritner 2014-10-06 17:55:38

回答

2

为什么不直接使用CASE条件像

CASE WHEN col2 is not null and col2 <> 0 THEN your_calculation 
1

你可以做一个子查询使用CASE语句来检查零和返回NULL。 然后您可以在子查询上运行您当前的查询。

我看到使用的情况将是丑陋的,你有3个表达式COALESCE

SELECT 
CAST(COALESCE(col2 , (col3/7), (col4/30)) as money) col2 
, CAST(COALESCE(col3, (col2*7), (col4/30*7))as money) col3 
, CAST(COALESCE(col4, (col3/7*30),(col2*30))as money) col4 
from 
(SELECT case when col2 =0 then NULL else col2 end as col2, 
    case when col3 =0 then NULL else col3 end as col3, 
    case when col4 =0 then NULL else col4 end as col4 
from Table1) T 
2

虽然COALESCE可以让你用一个特定值代替NULL,NULLIF将允许您用替换特定值空值。你可以使用后者0,并与像这样结束:

, CAST(
    COALESCE(
     NULLIF(col2, 0), 
     NULLIF(col3, 0)/7, 
     NULLIF(col4, 0)/30 
    ) AS money 
) AS col2 
, CAST(
    COALESCE(
     NULLIF(col3, 0), 
     NULLIF(col2, 0) * 7, 
     NULLIF(col4, 0)/30 * 7) 
    ) AS money 
) AS col3 
, CAST(
    COALESCE(
     NULLIF(col4, 0), 
     NULLIF(col3, 0)/7 * 30, 
     NULLIF(col2, 0) * 30 
    ) AS money 
) AS col4 

还比较长,如果你问我,但绝对比使用的情况下更短。每个表达式中的最后一个NULLIF可能是不必要的,为了一致性,我将它们留在那里。也许你可以在每个地方添加0的第四个参数,只是为了确保结果永远不是NULL。

0

可以使用NULLIF功能:

,CAST(COALESCE(NULLIF(col2,0), NULLIF(col3/7,0), NULLIF(col4/30,0)) as money) col2 
,CAST(COALESCE(NULLIF(col3,0), NULLIF(col2*7,0), NULLIF(col4/30*7,0))as money) col3 
,CAST(COALESCE(NULLIF(col4,0), NULLIF(col3/7*30,0),NULLIF(col2*30,0))as money) col4