0

Hi guys I want to get the summation of column values from my sqlite database in android. and am trying to use this to get me the sum of column KEY_COST.

public Cursor fetchAllCost() {
   return mDb.query(
                     DATABASE_TABLE, 
                     new String[] { "SUM(KEY_COST)"}, 
                     null, 
                     null, 
                     null, 
                     null, 
                     null);
}

but its giving me a cursor and I do not know how to get the value from the Cursor object. Any one help!!!

3 Answers 3

1

You can return scalar values like so:

public int getColumnData() {

    mDb = mDbManager.getReadableDatabase();
    final SQLiteStatement stmt = mDb
            .compileStatement("SELECT SUM(KEY_COST) FROM...");

    // Cast as appropriate
    return (int) stmt.simpleQueryForLong();
}

Or alternatively, depending on the data type use simpleQueryForString().

Sign up to request clarification or add additional context in comments.

Comments

0

You should just move to the first result in the cursor with cursor.moveFirst() and then you can do cursor.getInt(1) to get the scalar value.

Comments

0

rawQuery
Sum value is on first column - cursor.getInt(0);

Cursor cursor = database.rawQuery(
    "SELECT SUM(" + COL_NAME + ") FROM " + TABLE_NAME, null);
if(cursor.moveToFirst()) {
    return cursor.getInt(0);
}


query

String[] columns = new String[] {                
                 "sum(" + DbHelper.C_COUNT_OF_WORDS + ")"
                };

        String where = null;
        String whereArgs[] = null;
        String groupBy = null;
        String having = null;
        String order = null;
        String limit = null;

        database = dbHelper.getReadableDatabase();
        Cursor cursor = database.query(DbHelper.TABLE_STATISTICS, columns, where, whereArgs, groupBy, having, order, limit);

        if(cursor.moveToFirst()) {
            return cursor.getInt(0);            
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.