![](/img/trans.png)
[英]How to calculate days of weeks between two dates with SQLite in Android
[英]Android sqlite - how to calculate the difference between 2 REAL entries in sqlite?
在 Android/Java 中,当输入一个值时,我试图在 sqlite 中计算和存储两个值之间的差异。 我的桌子看起来像这样:
当权重添加/存储在表中的“重量”列中时,“Diff_Weight”列应接收“重量(N)-重量(N-1)”。 示例:Diff_Weight 的最后一个单元格(第 6 行)= 88.0 - 55.2 = 32.8。 // 第 5 行应为“-0.7”等。它们的类型是 REAL(col Weight & col Diff_Weight)。
这个32.8应该在88.0加入表的同时计算并加入。
到目前为止,我已经阅读了很多教程,但不知道如何继续。 (我在数据库中创建和插入的代码很好,但读取在某种程度上更复杂)。
我读取条目的代码非常糟糕,因为我不知道如何设置它:
public Bouble getData() {
String selectQuery= "SELECT * FROM " + TABLE_NAME2 + " ORDER BY COL_4 DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(TABLE_NAME2, null);
result2 = Double.valueOf(cursor.getString(cursor.getColumnIndex("Weight")));
result1 = Double.valueOf(cursor.getString(cursor.getColumnIndex("Weight")-1));
insertdata(result2-result1); //insert in row 6 of Diff_Weight
return
}
有人可以帮忙吗?
如果不清楚,我需要一些关于 sqlite 命令和 java 的帮助来获得差异结果。
简单地说,您可以通过加入同一个表来获取数据
SELECT a.id, a.weight, b.weight, (b.weight - a.weight) FROM TABLE_NAME2 a
join TABLE_NAME2 b on (b.id = a.id + 1);
一种方法是使用lag()
窗口函数来获取前一行的值(按id
排序;使用时间戳会更好,但在将日期和时间分成不同的列和不使用日期格式之间有意义的排序,这更容易。):
SELECT id, weight,
round(coalesce(weight - lag(weight, 1) OVER (ORDER BY id), weight), 1) AS diff_weight
FROM example
ORDER BY id
这使
id weight diff_weight
---------- ---------- -----------
1 22.0 22.0
2 22.2 0.2
3 55.0 32.8
4 55.9 0.9
5 55.2 -0.7
6 88.0 32.8
如果您愿意,您可以像普通表一样使用此查询的视图。 像这样动态生成差异的优点是,如果现有权重值发生变化,则不必更新依赖于它的所有内容。
好的,经过长时间的搜索,这是一个可能的结果(sqlite + java):
这是代码:
SQLiteDatabase db = this.getWritableDatabase();
//query the last row of the table
Cursor cursor = db.rawQuery("SELECT ID FROM TABLE_NAME2 ORDER BY ID DESC LIMIT 1", null);
cursor.moveToLast();
int lastID;
//handle the case if there is no row in your table
try {
lastID = cursor.getInt(0);
} catch (Exception e) {
lastID = 0;
}
Double lastWeight = 0.0;
//query the 'Weight' value
if (lastID >= 1) {
Cursor cursor2 = db.rawQuery("SELECT Weight FROM TABLE_NAME2 WHERE ID=" + lastID, null);
if (cursor2.moveToFirst()) { //this is boundary otherwise 'lastWeight' doesn't get the value
lastWeight= cursor2.getDouble(0);
}
} else {
lastWeight = 0.0;
}
//write the difference in the Diff_Weight column (=COL_5)
ContentValues cValues2 = new ContentValues();
//add your data in COL_1 to COL_4 here...
cValues2.put(COL_5, weight - lastWeight);
long id2 = db.insert(TABLE_NAME2, null, cValues2);
... 所以你从问题的表格照片中得到 Diff_Weight 列中的红色数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.