How to write sqlite select statement for NULL records

你。 提交于 2020-01-07 02:48:13

问题


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.

How do I write the statement so that it treats null values as 0.

My current sqlite statement: select sum(amount) from table1 gives error as it returns null.

Please help.


回答1:


You can use ifnull(x,y) or coalesce(x,y,z,...) function. 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.

select sum(ifnull(amount, 0)) from table1




回答2:


Accordgin to SQLite documentation:

The sum() and total() aggregate functions return sum of all non-NULL values in the group. If there are no non-NULL input rows then sum() returns NULL but total() returns 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'.



来源:https://stackoverflow.com/questions/4176517/how-to-write-sqlite-select-statement-for-null-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!