在除数中检查零或NULL

时间:2015-07-13 07:25:03

标签: sql sql-server

SELECT
    CASE 
        WHEN FIRST_NAME = 'alina' THEN (COMMISSION*RATE/TOTAL_DAYS)  
        ELSE REWARD 
    END AS reward
FROM testing;

我需要检查TOTAL_DAYS0还是NULL。我怎样才能做到这一点?对于NULL的情况,我可以使用ISNULL函数。

但是如何检查案例0NULL?如果TOTAL_DAYS ZERONULL,生成TOTAL_DAYS = 1

5 个答案:

答案 0 :(得分:1)

    select 
CASE 
    WHEN FIRST_NAME = 'alina' THEN  (COMMISSION * RATE/ISNULL(NULLIF(TOTAL_DAYS, 0), 1))  
    ELSE REWARD 
end as reward
    from testing;

答案 1 :(得分:1)

您可以结合使用NULLIFISNULL

SELECT
    CASE 
        WHEN FIRST_NAME = 'alina' THEN  (COMMISSION * RATE/ ISNULL(NULLIF(TOTAL_DAYS, 0), 1))  
        ELSE REWARD 
    END ASreward
FROM testing;

如果NULLIFNULLTOTAL_DAYS将返回0。然后,如果ISNULL返回1NULLIF将返回NULL。例如:

SELECT ISNULL(NULLIF(N, 0), 1) AS N
FROM(
    VALUES (3), (NULL), (0)
)t(N)

返回:

N
-----------
3
1
1

答案 2 :(得分:0)

您可以使用coalescenull翻译为1,将greatest翻译为0:

SELECT CASE WHEN FIRST_NAME = 'alina' 
            THEN commission * rate / GREATEST(COALESCE(total_days, 1), 1)
            ELSE reward END AS reward 
FROM testing;

答案 3 :(得分:0)

如果有效,请检查一下。

        select 
    CASE 
        WHEN FIRST_NAME = 'alina' THEN CASE WHEN COALESCE(TOTAL_DAYS,0) = 0 THEN 0 ELSE (COMMISSION*RATE/TOTAL_DAYS)  
        ELSE REWARD 
    end as reward
        from testing;

答案 4 :(得分:0)

试试这个:

SELECT
    CASE
    WHEN FIRST_NAME = 'alina' THEN
        commission * rate / COALESCE(NULLIF(total_days, 0), 1)
    ELSE
        reward
    END AS reward 
FROM
    testing;