2017-02-26 47 views
0

祝大家!從SQLite數據庫的一列中獲取總和和平均值

我想從android的sqlite數據庫的列中獲取總和和平均值。 搜索我發現了很多方法,我嘗試了他們不成功。

要獲取值的數量,我使用的列:

cursor.getCount() // with the cursor in the right column 

和它的作品。我的問題是如何獲得總和。 這是我「建」的方法:

public void setValues() 
{ 
    SQLiteDatabase db = mDbHelper.getReadableDatabase(); 

    String[] projection = { 
      _ID, 
      DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES, 
    }; 


    Cursor curs = db.query(
      DiabeticContract.DiabeticEntry.TABLE_NAME, 
      projection,    
      null,     
      null,     
      null,    
      null,     
      null);     

    curs.moveToLast(); 

    double lastGlycValue = curs.getDouble(curs.getColumnIndex("Glycaemia")); 
    double percent = (lastGlycValue + 46.7)/28.7; 
    double mmol = ((percent - 2.15) * 10.929); 

    LastGlyc.setText(String.format("%.2f" ,lastGlycValue)); 
    Percent.setText(String.format("%.2f" ,percent)); 
    mMol.setText(String.format("%.2f" ,mmol)); 
} 

這是不cursor.getCount(),以使其更清晰。

謝謝你的幫助。

+0

你爲什麼不使用SQL查詢數據? – GurV

+0

我還使用內容提供商更好地處理數據 –

回答

1

SQL,你可以簡單地做:

select sum(col), avg(col) from table; 
+0

是的我知道,我在終端中試過它,它工作。但我不能從「機器人」。或者如果我可以,我不知道如何 –

+0

@Mark。 - 看看這個答案 - http://stackoverflow.com/questions/20582320/android-get-sum-of-database-column – GurV

+0

好吧謝謝。但是,我如何得到結果編號? –