SQL查询 - 处理Null值

时间:2014-02-12 15:50:23

标签: sql sql-server

我有一张下表

Name   Amount Paid  
-----------------------
Ali      500    500  
Baba     700    100  
Cam      300    Null   
Dave     Null   Null

我想要以下期望的结果:

Name   Amount Paid  
--------------------
Baba     700    100  
Cam     300    Null

我编写了以下SQL查询,但它无法正常工作

SELECT Name, Amount, Paid  
FROM Table_1  
WHERE PAID <> AMOUNT  

5 个答案:

答案 0 :(得分:1)

好吧,null <> nullnull,而null = null也是null,导致错误的情况。混乱?

您必须使用is null运算符单独检查null:

select
 Name, Amount, Paid
from Table_1
where 
 (Paid is not null and Amount is not null and Paid <> Amount) 
 or 
 not (Paid is null and Amount is null);

或者,在某些情况下,您可以轻松使用

coalesce(Paid, 0) <> coalesce(Amount, 0)

答案 1 :(得分:1)

如果将NULL视为零(假设这是有效的业务逻辑),那么它是否有效

SELECT Name,  ISNULL(Amount,0), ISNULL(Paid,0) as Paid
FROM   Table_1  
WHERE  ISNULL(Paid,0)  <> ISNULL(Amount,0)

答案 2 :(得分:1)

试试这个:

SELECT    Name, Amount, Paid  
FROM     Table_1  
WHERE ISNULL(PAID,0) <> ISNULL(AMOUNT,0)

答案 3 :(得分:1)

SELECT Name,Amount,ISNULL(付费,0)为付费 从表_1 WHERE ISNULL(付费,0)&lt;&gt; AMOUNT

答案 4 :(得分:1)

NULL表示未知,因此dmb不能说300&lt;&gt;空值。当NULL表示零时使用Coalesce(col,0):

SELECT Name, Amount, Paid  
FROM Table_1  
WHERE COALESCE(PAID,0) <> COALESCE(AMOUNT,0)