I want to create a Query that will give the total of all values in a single column of my SQLite datase.
I want this query to be within a method that returns the total as an int so that I can then further process it within a different activity.
How can I do so?
I have already created similar methods within my Database helper class (see below), but I do not know how to implement a query within SQLite to give the total.
Declaration and creation of database in Databasehelper: (the column i want the total for is COL_MED)
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 10;
// Database Name
private final static String DATABASE_NAME = "MeditationDatabase";
// Contacts table name
private static final String TABLE_SCORE = "scores";
// Contacts Table Columns names
private static final String COL_SESSION = "sessionid";
private static final String COL_GAMETITLE = "game";
private static final String COL_NAME = "name";
private static final String COL_MED = "avgmeditation";
private static final String COL_MAX = "maxmeditation";
private static final String COL_AVGATT = "avgattention";
private static final String COL_MAXATT = "maxattention";
private static final String COL_SCORE = "score";
private static final String COL_DATE = "date";
/**
* Constructor
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method that creates the database
*/
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "(" + COL_SESSION
+ " STRING PRIMARY KEY, " + COL_GAMETITLE + " STRING, " + COL_NAME + " STRING, " + COL_MED + " INTEGER, "
+ COL_MAX + " INTEGER, " + COL_AVGATT + " INTEGER, " + COL_MAXATT + " INTEGER, " + COL_SCORE + " INTEGER, " + COL_DATE + " STRING " + ")";
db.execSQL(CREATE_TABLE_SCORE);
}
Potentially similar method that returns the number of entries in the DB:
public int getTotalGamesPlayed() {
SQLiteDatabase db = this.getWritableDatabase();
try {
return (int)DatabaseUtils.queryNumEntries(db, TABLE_SCORE);
} finally {
db.close();
}
}
EDIT:
Is this the correct query:
String query = "SELECT SUM(COL_MED) FROM " + TABLE_SCORE;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…