Calculate Sum of Column in SQLite Android

微笑、不失礼 提交于 2019-12-02 01:09:38

Correct way

 Cursor cursor = db.rawQuery("SELECT SUM(" + DbHelper.CART_TOTAL + ") as Total FROM " + DbHelper.CART_TABLE, null);

 if (cur.moveToFirst()) {

 int total = cursor.getInt(cursor.getColumnIndex("Total"));// get final total

You are missing Round Braces. Your query should be.

Cursor cur = db.rawQuery("SELECT SUM(" + (DbHelper.CART_TOTAL) + ") FROM " + DbHelper.CART_TABLE, null);

The answer given by @MD in detail :

SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT SUM(" + DBHelper.COST + ") as Total FROM " + DBHelper.EXPENSE_TABLE, null);
    if (cursor.moveToFirst()) {
        int total = cursor.getInt(cursor.getColumnIndex("Total"));
        return total;
    }
  • DBHelper: some Database Helper Class
  • DBHelper.COST : Name of column for which cost is calculated
  • EXPENSE_TABLE : name of the table
//Sample calculate SUM Value
    public int getSumValue(){
        int sum=0;
        database=dbHelper.getReadableDatabase();
        String sumQuery=String.format("SELECT SUM(%s) as Total FROM %s",dbHelper.VALUE,dbHelper.TABLE_NAME);
        Cursor cursor=database.rawQuery(sumQuery,null);
        if(cursor.moveToFirst())
            sum= cursor.getInt(cursor.getColumnIndex("Total"));
        return sum;
    }

Note that: database is SQLiteDatabase, dbHelper is DatabaseHelper class (you create it and set name DatabaseHelper), dbHelper.VALUE is column name, dbHelper.TABLE_NAME is table name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!