![](/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.