简体   繁体   English

如何为空记录编写sqlite select语句

[英]How to write sqlite select statement for NULL records

I have a column which contains null values in some of the rows. 我有一列在某些行中包含空值。

I want to do sum of the column values by writing a select statement in sqlite. 我想通过在sqlite中编写一条select语句来对列值求和。

How do I write the statement so that it treats null values as 0. 如何编写该语句,以便将空值视为0。

My current sqlite statement: select sum(amount) from table1 gives error as it returns null. 我当前的sqlite语句:从table1中选择sum(amount)会返回错误,因为它返回null。

Please help. 请帮忙。

Accordgin to SQLite documentation : 根据SQLite文档

The sum() and total() aggregate functions return sum of all non-NULL values in the group. sum()和total()聚合函数返回组中所有非NULL值的和。 If there are no non-NULL input rows then sum() returns NULL but total() returns 0.0. 如果没有非NULL输入行,则sum()返回NULL,但total()返回0.0。 NULL is not normally a helpful result for the sum of no rows but the 对于没有行的总和,空值通常不是有用的结果,而是

So I guess you'd better use total() instead of sum() in case you expect that the result be 'non-null'. 因此,我猜您最好使用total()而不是sum(),以防您期望结果为“非null”。

You can use ifnull(x,y) or coalesce(x,y,z,...) function. 您可以使用ifnull(x,y)或coalesce(x,y,z,...)函数。 Each of them return the first non-null value from the parameter list from left to right. 它们每个都从左至右从参数列表返回第一个非空值。 ifnull has exactly two parameter whereas coalesce has at least two. ifnull具有正好两个参数,而凝聚具有至少两个。

select sum(ifnull(amount, 0)) from table1 从表1中选择sum(ifnull(amount,0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM