SQLite:获取一列中所有值的总和

时间:2014-07-31 20:24:54

标签: android sql sqlite

我想创建一个Query,它将在我的SQLite数据的单个列中提供所有值的总和。

我希望这个查询位于一个方法中,该方法将total返回为int,以便我可以在不同的活动中进一步处理它。

我该怎么办?

我已经在我的数据库助手类中创建了类似的方法(见下文),但我不知道如何在SQLite中实现一个查询来给出总数。

在Databasehelper中声明和创建数据库:(我希望总数为 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);

    }

返回数据库中条目数的潜在类似方法:

public int getTotalGamesPlayed() {
    SQLiteDatabase db = this.getWritableDatabase();
    try {
        return (int)DatabaseUtils.queryNumEntries(db, TABLE_SCORE);
    } finally {
        db.close();
    }
}

编辑:

这是正确的查询:

String query = "SELECT SUM(COL_MED) FROM " + TABLE_SCORE;

1 个答案:

答案 0 :(得分:0)

阅读documentation;您可以使用sum()total()

列的名称不是COL_MED;这是符号的名称,其值是列的名称。 与TABLE_SCORE类似,您必须将其值插入SQL查询中:

int getSumOfAllAvgMeditations() {
    SQLiteDatabase db = getWritableDatabase();
    try {
        String sql = "SELECT TOTAL(" + COL_MED + ") FROM " + TABLE_SCORE;
        return (int)DatabaseUtils.longForQuery(db, sql, null);
    } finally {
        db.close();
    }
}