iphone - 在 SQLite 中添加同一列的所有元素

标签 iphone sqlite

我的 SQLite 表 (OrderTable) 中有 价格 列。我想添加价格列中的所有值,以便获得总价。

例如,价格列有 3 个值:

150.00  
250.00  
300.00 

如何使用 SQLite 查询获取总金额 (700.00)?

最佳答案

total(X),其中 x 是列名称。 Click在这里了解有关 sqlite 中数学函数的更多信息。

从订单表中选择总计(价格)AS TOTAL_PRICE; //结果为浮点值

SELECT sum(Price) AS TOTAL_PRICE FROM OrderTable //将得到 int 值

示例

CREATE TABLE OrderTable (Price Integer);
INSERT INTO OrderTable VALUES (1);
INSERT INTO OrderTable VALUES (2);
INSERT INTO OrderTable VALUES (3);
INSERT INTO OrderTable VALUES (NULL);  // NULL

SELECT total(Price) AS TOTAL_PRICE FROM OrderTable;  // output 6.0

SELECT sum(Price) AS TOTAL_PRICE FROM OrderTable     // output 6

来自reference

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 SQL standard requires it and most other SQL database engines implement sum() that way so SQLite does it in the same way in order to be compatible. The non-standard total() function is provided as a convenient way to work around this design problem in the SQL language.

The result of total() is always a floating point value. The result of sum() is an integer value if all non-NULL inputs are integers. If any input to sum() is neither an integer or a NULL then sum() returns a floating point value which might be an approximation to the true sum.

Sum() will throw an "integer overflow" exception if all inputs are integers or NULL and an integer overflow occurs at any point during the computation. Total() never throws an integer overflow.

关于iphone - 在 SQLite 中添加同一列的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7396948/

相关文章:

java - Objective-C 方法重载

sqlite - 如何从sqlite中的多个表中删除数据?

objective-c - 如何在 objective-c 中正确地防止 SQL 注入(inject)我的查询

iphone开发-豹子还是雪豹?

iPhone设备 token 在MYSQL数据库中存储多次

ruby-on-rails - Active Admin - 根据第一个下拉菜单刷新第二个下拉菜单,Ruby on Rails

Android samsung s6 SM-G920F marshmallow 卸载应用程序时无法删除数据

SQLite:如何创建两个查询的不相关元素的组合?

iphone - 如何在 Objective-C 中编写带有 CRLF 换行符的文件?

iphone - NSFetchedResultsChangeDelete 未被触发