开发者

Adding all elements of same column in SQLite

I have Price column in my SQLite table (OrderTable). I want开发者_JAVA百科 to add all the values in Price column, so that I can have the total price.

For example Price column has 3 values :

150.00  
250.00  
300.00 

How can I get the total amount (700.00) using SQLite query?


total(X) where x is the column name. Click here to know more about math function in sqlite.

SELECT total(Price) AS TOTAL_PRICE FROM OrderTable; // will result float value

SELECT sum(Price) AS TOTAL_PRICE FROM OrderTable // will result int value

SAMPLE

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

From the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜