2013-02-04 51 views
0

我有一个查询如何通过包含空值编写一个查询太

SELECT sum(cash) from bought_cash WHERE uid=1 AND source NOT IN ('a', 'b') 

给出结果为140

SELECT sum(cash) from bought_cash WHERE uid=1 AND source IN ('a', 'b') 

NULL

SELECT sum(cash) from bought_cash WHERE uid=1 

给人造成为240

SELECT sum(cash) from bought_cash WHERE uid=1 and source is null 

给出的结果100

如何编写一个查询,以便第一个查询通过包含空值给出结果为240

+0

你确定它应该是240的结果,我看不出为什么这不会是正确的。 – bretterer

+0

您的意思是您希望“NULL”值位于您的第一个查询中吗? –

+1

在第一个查询中,iam不包括where子句中的空值,所以结果应该包含空值对吗? – shanks

回答

1

你也可以尝试下:

select sum(cash) 
from bought_cash 
where uid = 1 and (source is null or source not in ('a', 'b')) 
+0

谢谢你的工作。但为什么不包含缺省值的空值? – shanks

+0

,因为空值符号为sql标准的缺失值,并且当您在IN标准中包含空值时,NULL变为未知值 – veljasije

+1

实际上它是默认包含的,但对于SUM操作,您将添加NULL,不包含任何价值。它像1 +空= 1 –

0

你可以尝试这样的事:

select sum(cash) from bought_cash 
    where uid=1 and isnull(source, 'c') not in ('a', 'b') 

这应该映射为空项的值“C”,这是不是“A”或“B”,所以应该被包括在结果集。

相关问题