获取 SQLite 中列值的总和 [英] Getting sum total of column values in SQLite
问题描述
我在 SQLite 中有一个具有这种结构的表:
I have a table in SQLite with this structure:
String CREATE_TOTAL_PRICE = "CREATE TABLE " + TOTAL_PRICE + "("
+ KEY_TPID + " INTEGER PRIMARY KEY,"
+ KEY_TPRICE + " REAL" + ")";
我正在尝试获取 KEY_TPRICE 列的所有列值的总和.我正在使用这种似乎有效的方法:
I am trying to get the sum total of all column values of column KEY_TPRICE. I am using this method which seems to work:
public int getTotalOfAmount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(total_price) FROM " + TOTAL_PRICE, null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
但是当显示值时问题就来了.
But the problem comes when the value is being displayed.
你看到我输入的数据为 50.01,5.5
,当得到总和时,我得到 55
,但事实并非如此.
You see i have data input as 50.01,5.5
and when getting the sum total i get 55
which is not really the case.
当我在外部运行查询时,实际总数是 55.51
.
The real total is 55.51
when i run the query externally.
我已经尝试将 REAL,INTEGER, FLOAT,DOUBLE
设置为我的列数据类型,但仍然
I have tried setting REAL,INTEGER, FLOAT,DOUBLE
as my column data type but still
究竟是什么对我的数字进行四舍五入?请协助我提出建议.
What exactly is rounding up my figures? Please asssist me with suggestions.
推荐答案
我认为你收到 55 是因为你把它读成int"
I think you are receiving 55 because you are reading it as "int"
int i = c.getInt(0);
这就是它被转换"为 int (55) 的原因.
That's why it is being "converted" to int (55).
根据问题 https://stackoverflow.com/a/17947203/4860513 ,似乎 SUM()将返回与您正在阅读的列格式相同的数字.因此,尝试读取双精度/浮点数并分享结果:
According to question https://stackoverflow.com/a/17947203/4860513 , it seems that SUM() will return a number in the same format of the column that you are reading. So, try it to read is a double/float and share the result:
float i = c.getFloat(0);
double i = c.getDouble(0);
这篇关于获取 SQLite 中列值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!