我的 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
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/